Messenger and Service in Android

Generally to get some result back from service or intent service we use Broadcast receiver. That is, service send a broadcast and in activity we register a receiver and and do some operations according to the result we got from service.

Here I am going to tell a alternate way to get the result back from service or intent service. It is a simple and effective way using Handler and Messenger.

Consider, we have to download a image from network

  button.setOnclickListener(new OnClickListener() {
    public void onClick(View v) {
      Intent intent = new Intent(MainActivity.this, DownloadService.class);
      intent.putExtra(DownloadService.EXTRA_MESSENGER, new Messenger(handler));


and our handler looks like this,

  private Handler handler=new Handler() {
    public void handleMessage(Message msg) {
      Toast.makeText(MainActivity.this, "Download complete!", Toast.LENGTH_LONG).show();

So after image is downloadeded through intent service we will get the callback in handler through Messenger. Now we will see the intent service. The onHandleIntnet() of intentService will look like this,

  public void onHandleIntent(Intent i) {
   // .... image downloading code goes here
   int result = Activity.RESULT_OK;
   Bundle extras=i.getExtras();
   if (extras!=null) {
      Messenger messenger=(Messenger)extras.get(EXTRA_MESSENGER);
      Message msg=Message.obtain();
      try {
      } catch (android.os.RemoteException e) {
        Log.w("DownloadService", "Exception sending message", e);

Thereby, we are passing the result back to activity through messenger.

Happy Coding


Popular posts from this blog

Open Gallery and get the selected image in appplication

Dismiss or Cancel dialog by swipe gesture

AlarmManager and Notification in Android