Google Android Application Development Utilizing Background Processes 

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.

 [code] 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
[/code]

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:

 [code] 
@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); 
} 
[/code] 

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.

 [code] 
// 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!"); 
} 
[/code] 

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.

 [code] 
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"); 
} 
[/code] 

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.

 [code] if (timer != null) {   timer.cancel(); } [/code] 

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.

Teaser: 

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

He has expertise in using a

He has expertise in using a wide range of open source and commercial tools WASCE Eclipse Mule ESB Mule Galaxy EZlegacy Active MQ Birt and DB2 express C and technologies GWT RSS and Atom ...Summary This tutorial demonstrates how to develop web service with Java 2. Eclipse IDE is also used to develop a web service and deploy it in the WASCE. There is also a Stock-Quote service example in a remote location not in local host developed in .NET platform and this tutorial will show how to invoke it using a J2ME client....

Does one have to create a

Does one have to create a separate MainService class? If so, what should that include?

Hi, This is a great article

Hi, This is a great article and help. could you pls provide the MainService.java class Thx

pls explain the

pls explain the caculateSpeed() method......?

Sapna, sorry for the

Sapna, sorry for the delay. These properties are local variables used by the service class. The "timer" is a java.util.Timer object, for more information you can take a look into the documentation. "currentlocation" is a property that holds the current device location and it is an android.location.Location object. About the method "calculateSpeed()", it is used to implement business logic. [code] private Timer timer = new Timer(); private Location currentLocation; [/code]

This article is good but

This article is good but there are a lot of things that must be described such as what is the timer, currentlocation, calculateSpeed. So please either define the variables or provide the source code.