Latest Entries

Tags

Links

Android Development Part 2: Service

This tutorial assumes that you know how to make basic Activity. On this tutorial, we are going to tackle how to make and run Services. A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use. In simple terms, it's an application that runs in background.

There are two types of Service: started and bound. A started service is when an application component (such as an Activity) starts it by calling startService(). A Bound service is when an application component binds to a service by calling bindService().

service_lifecycle.png

The way you create a service is very similar way you create an activity. You must create a class that extends Service.

public class MyService extends Service {

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public void onCreate() {
		Toast.makeText(this, "Service created", Toast.LENGTH_LONG).show();
	}

	@Override
	public void onDestroy() {
		Toast.makeText(this, "Service destroyed", Toast.LENGTH_LONG).show();
	}

}

If you noticed, returned null in the onBind() method. It's to make a distinction that this is a started service and not a bound one. The way you run a service is similar to the way you run an Activity:

Intent intent = new Intent(this, MyService.class);
startService(intent);

We create an intent object, passing 'this' in the parameter as we want the service to run in "this" Activity. The second parameter is the Service class itself. We can exit the application, and the service will still continue to run! We can stop an activity by using another method called stopService().

Intent intent = new Intent(this, MyService.class);
stopService(intent);

Again, we must pass an intent object to the stopService() method.

A Bound service is more complex. We must also extend from the Service class, but this time, we must make it a Bound service.

public class MyBound extends Service {

   private final IBinder mBinder = new LocalBinder();
    /**
     * Class used for the client Binder.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with IPC.
     */
   public class LocalBinder extends Binder {
    	MyBound getService() {
         // Return this instance of LocalService so clients can call public methods
    		return MyBound.this;
      }
   }

   @Override
   public IBinder onBind(Intent intent) {
      return mBinder;
   }

}

As you can see, we created an inner class called LocalBinder, which extends the Binder class. The class has a method called getService(), which returns MyBound service itself, of Binder class.

In the Activity part of the application, we have to do quite a few tedious things. First, we'll need to create three member variables type MyBound (our bound service), a boolean which keeps track if the application has binded to the service or not, and finally a ServiceConnection variable that defines callbacks for service binding.

   MyBound mService;
   boolean mBound = false;
   private ServiceConnection mConnection = new ServiceConnection() {
      public void onServiceConnected(ComponentName className,
                IBinder service) {
         // We've bound to LocalService, cast the IBinder and get LocalService instance
         LocalBinder binder = (LocalBinder) service;
         mService = binder.getService();
         mBound = true;
      }

      public void onServiceDisconnected(ComponentName arg0) {
         mBound = false;
      }
   };

mConnection is a ServiceConnection object which overrides the onServiceConnected() and onServiceDisconnected() methods. In onServiceConnected() method, binder (LocalBinder) calls getService() which returns the bounded service that we created, finally sets mBound to true (note that we set this to false in onServiceDisconnected() )

Finally, in the onStart() and onStop() methods, we do the following:

   @Override
   protected void onStart() {
      super.onStart();
      // Bind to LocalService
      Intent intent = new Intent(this, MyBound.class);
      bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
      Toast.makeText(this, "onStart: Bind to LocalService", Toast.LENGTH_SHORT).show();
    }
    
    @Override
   protected void onStop() {
      super.onStop();
      // Unbind from the service
      if (mBound) {
         unbindService(mConnection);
         mBound = false;
         Toast.makeText(this, "onStop: Unbind from the service", Toast.LENGTH_SHORT).show();
      }
   }

We create an Intent object for our MyBound bound service. Then we pass it to the bindService() class which finally runs it. mConnection is our ServiceConnection variable type which is responsible for callbacks and connection between the bound service and application. We pass it to unbindService() method if we wish to unbind the bound service itself from the application.

If we wish to run a method from the bound service, we simply do the following:

mService.METHODNAME();

That's all for this tutorial! Please see the Android Developers site for more information.