Author Archive

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.

JFreeChart is an open-source Java based library which allows the creation of complex charts in a simple way.

Supported chart types include:

  • X-Y charts (line, spline and scatter);
  • Pie charts;
  • Gantt charts;
  • Bar charts (horizontal and vertical, stacked and independent);
  • Single valued (thermometer, compass, speedometer).

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