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() {
  
    @Override
    public void onClick(View v) {
      Intent intent = new Intent(MainActivity.this, DownloadService.class);
      intent.setData(Uri.parse("https://actiontreeservice.ca/files/trees.png"));
      intent.putExtra(DownloadService.EXTRA_MESSENGER, new Messenger(handler));
      startService(intent);
    } 

  });


and our handler looks like this,

  private Handler handler=new Handler() {
    @Override
    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,



  @Override 
  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();
      
      msg.arg1=result;
      
      try {
        messenger.send(msg);
      } 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


Comments

Popular posts from this blog

Open Gallery and get the selected image in appplication

AlarmManager and Notification in Android

Dismiss or Cancel dialog by swipe gesture