Android is one of the fastest growing operating systems and software stacks for smartphones. OS smartphones ranked second among all smartphone OS handsets sold in the U.S. in the first quarter of 2010. Dell, HTC, Motorola and Samsung are some of the manufacturers using this operating system.
Google opened the source code under an Apache License and now the Android SDK allows developers to write managed code in the Java language, controlling the device via Google-developed Java libraries. The SDK includes a comprehensive set of development tools, such as a debugger, libraries, a handset emulator, documentation, sample code and tutorials.
Applications that run in the background are supported in Android in contrast to iPhone. All of these facts stimulate me to research this interesting technology. I decided to make an application running in the background and receiving the GPS location. The main goal was to inform the user not to write or read text messages while he or she is driving.
It is pretty easy to develop an Android application, especially if you are using Eclipse. You can download the latest version of the Android SDK from the official site. There are a lot of tutorials explaining how to install and use the SDK in Eclipse, if you are a beginner you can take a look at the developer’s guide.
Utilizing the GPS Module
As you may know smartphones have a gps module which provides the current location. This feature is used in many applications. To implement it you have to modify the AndroidManifest.xml, this is the main configuration file.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
With these permissions you tell to the application that the GPS module will be used and the application is given access to it.
The Activity Class
There is one very important class in an application’s overall lifecycle – the Activity class. It takes care of creating a window for you in which you can place your UI. But this activity is not enough to create a background process. It should be used in conjunction with another object from the ContextWrapper to achieve the behavior of an application component that runs in the background and doesn’t interact with the user. This functionality is given up by the Service class. Both the activity and the service should be declared in the android manifest file.
My idea is to create a main activity class and in the onCreate() method call the service. But when something is started, there needs to be a way to stop it. The best place to stop the service is in the onDestroy() method of the main activity. These two methods are overridden because the main activity has to extend the Activity.java class. They look like:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
// setup and start MainService
MainService.setMainActivity(this);
Intent svc = new Intent(this, MainService.class);
startService(svc);
} catch (Exception e) {
Log.e(">>>", "Problem creating the UI", e);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// stop MainService
Intent svc = new Intent(this, MainService.class);
stopService(svc);
}
This is how the activity class looks. The service class will manipulate the GPS module data. It will get the location in a time interval, get the speed or calculate it if it is not available and finally if the speed is more than 10km/h it will inform the user not to use the phone’s features while driving in order to avoid accidents.
The Service Class
As the main activity extends Activity.java class, the service should extend the Service.java class. The service is started in the overridden method onCreate() of the class.
// service business logic
private void startService() {
TimerTask timerTask = new TimerTask(){
public void run() {
getUpdateLocation();
}
};
timer.scheduleAtFixedRate(timerTask,0,UPDATE_TIME_INTERVAL);
Log.i(getClass().getSimpleName(), "Timer started!");
}
First a timer object is needed which will take care of calling the service. To schedule the timer you have to prepare a TimerTask instance, which calls your business logic. In the example it is called the getUpdateLocation() method, its functionality will be explained later in this post. The timer is scheduled with the timer task and the specified time interval passed as a constant.
Lets take a look at the getUpdateLocation() method. As the title says, the method gets the location from the LocationManager.java class. The locations are separated by providers, so they are filtered with a criteria. Some GPS providers send the speed of the device. But if the speed is not received, it can easily be calculated as a quotient of the distance between the current and previous location with the subtraction of the two times.
private void getUpdateLocation() {
Log.i(getClass().getSimpleName(), "background task - start");
// get the system location service
locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
// create criteria to filter the providers
Criteria criteria = new Criteria();
bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
date = new Date();
if(currentLocation == null){
currentLocation = locationManager.getLastKnownLocation(bestProvider);
currentDate = new Date();
}
float speed = calculateSpeed(location);
// speed > (10km/h = 2.78m/s)
if(speed > SPEED_LEVEL){
Looper.prepare();
Context context = getApplicationContext();
CharSequence text = MESSAGE;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
Looper.loop();
}
// set the currentLocation and currentDate with new values
// for the next iteration
currentLocation = location;
currentDate = date;
Log.i(getClass().getSimpleName(), "background task - end");
}
The user will be informed with a warning message, if the calculated speed is more than a specified value. This is the business logic, but there is one other thing to take care of – the timer. The timer is started in the onCreate() method of the service class. It will be stopped in the onDestroy() method of the service class. The cancel() method will then be called in order to cancel the timer and remove any scheduled tasks.
if (timer != null) {
timer.cancel();
}
The completed application will run in the background and inform the user with a message that his or her speed is more than 2.78 meters per second.
Google recently announced that they began factoring in web site load time into their search engine ranking algorithm. This has brought the importance of a fast load time front and center even though “fewer than 1% of search queries will change as a result” of this update. MentorMate.com likely was not impacted very significantly from this change to Google’s ranking algorithm; however, we still decided to optimize our site’s load time. We did this because Google showed that “delays of under a half-second impact business metrics.” It’s better to be safe than sorry, and besides, it’s not that difficult to optimize your site. We recommend you do the same with your web site, here are nine easy ways to do just that:
Scripts block parallel downloads. While a script is downloading, the browser will wait until it finishes before downloading anything else. This is why it is recommended that you get everything else out of the way before having your users download scripts.
Simply enter your web page URL in Pingdom’s Full Page Test Tool. This tool will color-code any broken links/references in red so you can easily identify them.
When image dimensions are not specified in the HTML and/or CSS of a web page, the web server must spend resources calculating these dimensions. It’s particularly important to specify the dimensions of images being used in conjunction with heavy Javascript image-manipulation libraries.
This is another spot in which Pingdom’s Full Page Test Tool comes in handy. Enter your URL and look for any file references to external domains. If possible, copy these files onto your own domain and link to them locally to minimize DNS requests.
Libraries and external widgets need to be chosen carefully. Sometimes it’s worth sacrificing load time for particularly engaging/useful libraries and/or widgets; however, sometimes you can live without the library and/or widget. For example, on MentorMate.com we felt it was worth sacrificing Sexybuttons for better load time, but sacrificing load time for Shadowbox. External widgets can be particularly bad for a site’s load time because of their reliance on external servers.
These days, gzip comes pre-installed on most web servers. You can check to see if gzip is running your server quite easily using Google’s Firebug “Speed Test” extension. Open Firefox, visit the web site you’d like to optimize, and open Firebug. From there, click “Analyze Performance” and select the “Resources” tab. Then you can expand any file to view details. If gzip is installed and compressing the element you are viewing, you will see what is highlighted in red in the following screenshot:

Depending on the complexity of your site, it can be quite time consuming to merge all CSS into one file. The same goes for Javascript. This is why Minify was developed. Minify “combines multiple CSS or Javascript files, removes unnecessary whitespace and comments, and serves them with gzip encoding and optimal client-side cache headers.” Then you simply need to install it on your site, select the files you want it to serve together, change some references in your header, and you’re good to go. This will minimize your site’s load time by further helping to reduce HTTP requests.
For instance, we use the IE PNG FIX for IE6 PNG transparency compatibility. This script adds an extra second to web site load time. For this reason, we only load the script if the visitor is running IE6 by applying an IE6-specific stylesheet which references the IE PNG FIX. This way the extra load time will only impact IE6 visitors.
We simply added the following line of code to our header:
<!--[if IE 6]><link rel="stylesheet" type="text/css" href="css/ie6.css" /><![endif]-->
A CSS sprite is the combination of multiple images into one. Then CSS is used to reference different aspects of the image where needed. This reduces load time by minimizing all of these images into only one HTTP request. CSS Tricks has a good example of CSS sprites.
JFreeChart is an open-source Java based library which allows the creation of complex charts in a simple way.
Supported chart types include:
I am going to explain how to use the chart library and how to create a bar chart with a custom color. To create a chart with JFreeChart library, first you have to make a Dataset object. The chart is generated from this data collection. Next you have to instate the class DefaultCategoryDataset, which is passed to the chart object. In the code below as a data source is used ArrayList, which may come from data base.
// load the data
double[] data = new double[jobTitles.size()];
for (int i = 0; i < jobTitles.size(); i++) {
data[i] = jobTitles.get(i).getCount();
}
// create the data set
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
for (int i = 0; i < data.length; i++) {
dataset.setValue(data[i], "Profit1", jobTitles.get(i).getTitle());
}
The next step is to do an object from chart type. The library uses a class named JFreeChart to display the chart. This chart object is an instance, which comes from the method createBarChart of the static class ChartFactory. The method takes as a parameter the formed collection (dataset). There are many properties, which you can pass to the constructor, such as labels, orientation, etc. It is possible to change colors, size, scale and many other characteristics.
You have ready object now and the next step is to send the chart to the web page. For this purpose, the library includes a class named ChartUtilities that provides several methods for saving charts to files or writing them out to streams in JPEG or PNG format. The methods from this class can be used for creating JPEG images for static web pages. The goal, however, is not to save the chart in a hard drive; the goal is to pass the graphic to the application. To do that, you can use the servlet technology and display the dynamic data stream in the jsp pages.
Consequently the next step is to generate BufferedImage from your chart object and to transfer this stream through the session. You should also write the image in the http response writer.
// create the chart
final JFreeChart chart = ChartFactory.createBarChart("Allocation of Duties",
"Values", dataset, PlotOrientation.VERTICAL, true, true, true);
// set custom color
GradientPaint gradientpaint0 = new GradientPaint(0.0F, 0.0F,
new Color(209, 228, 246), 0.0F, 0.0F, new Color(82, 141, 201));
BarRenderer r = (BarRenderer)chart.getCategoryPlot().getRenderer();
r.setSeriesPaint(0, gradientpaint0);
ChartRenderingInfo info = null;
HttpSession session = request.getSession();
try {
// create RenderingInfo object
response.setContentType("text.html");
info = new ChartRenderingInfo(new StandardEntityCollection());
BufferedImage chartImage = chart.createBufferedImage(640, 400, info);
session.setAttribute("chartImage", chartImage);
PrintWriter writer = new PrintWriter(response.getWriter());
ChartUtilities.writeImageMap(writer, "imageMap", info, false);
writer.flush();
} catch (Exception e) {
e.printStackTrace();
}
Finally you should write the servlet. This is a Java object, which dynamically answers requests and built response to the client. Each servlet has two main methods – doGet(HttpServletRequest request, HttpServletResponse response) and doPost(HttpServletRequest request, HttpServletResponse response). You need to get the chart stream from the session in the servlet. The image is set to an attribute named chartImage in the session. You have to get http session instance from the request and then to retrieve the previously set attribute.
// Process the HTTP Get request
public void mdoGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// get the chart from session
HttpSession session = request.getSession();
BufferedImage chartImage = (BufferedImage)session.getAttribute(“chartImage”);
// set the content type so the browser can see this as a picture
response.setContentType(“image.png”);
// send the picture
PngEncoder encoder = new PngEncoder(chartImage, false, 0, 9);
response.getOutputStream().write(encoder.pngEncode());
}
// Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(re
Existing APIs for XML processing fall into two categories:
Cocoa offers a “complete” XML parser with the NSXML family of classes.
In the spirit of small and simple, iPhone developers have the NSXMLParser class to use. Because NSXMLParser only generates messages for a delegate, and doesn’t store data about the XML tree, it requires less memory and is better for accessing small pieces of data or parsing large XML documents. The basic operation of the NSXMLParser class will not be covered here. This is well documented in the Apple Programming Guide.
For devices like iPhone where memory usage is critical, using tree parser is not recommended. I guess that is why Apple doesn’t provide NSXMLDocument on iPhone/iPod touch. However, the model of event parsing may not be acceptable by your code. NSXMLParser is probably adequate, but it is not going to handle all your XML parsing needs. The biggest problem with this type of streaming parser is that you lose the structure of your data; your call-backs do not provide any context or hierarchy. Because of the above mentioned or by some other reason like often changing XML format [1] you may need to use something like DOM model implementation.
Well, if you’re going to need to parse very large XML documents, then you should probably consider NSXMLParser. What “very large” means depends a lot on the available memory you have to work with? The model of iPhone and the memory already in use by your app may prevent you from being able to use DOM model.
While DOM model usage may seem easier, NSXMLParser really excels in situations where you’re loading in many instances of the same kind of data, such as an address book or twitter feed. However, if memory is not an issue, I would recommend DOM model. It makes it easy to access the data you want and also allows you to manipulate the tree.