Skip to content

Using a seperate process

Devrath edited this page Apr 16, 2024 · 5 revisions

Add the process tag in the manifest

  • We mark the service to be run in a separate process as below
<service android:name=".service.PlayerService"
         android:process=":playerprocess"/>

Use messenger for communication

By the below way, a messenger can be passed between the Activity and Service as a binder.

  • Return messenger reference instead of IBinder reference
  • A messenger is just a reference to a handler.
  • Basically when you create a messenger we pass a handler during the creation.
  • A messenger can be transformed into a binder.
  • A messenger can be created from a binder.

How it works

Sending the message just from Activity to Service in one Direction

  1. Create a Handler to handle the messages to be sent into Service.
  2. Then create a new messenger object in the service.
  3. Next pass the handler reference into the service class
  4. Then we return the messenger as binder in the onBind method.

Service

mMessenger = Messenger(handler)

onBind(){
  return mMessenger.getBinder()
}
  1. Now we can recreate the messenger in the onServiceConnected() method using the iBinder reference.
  2. We can now create a message object and pass the message to the messenger Activity
onServiceConnected(ComponentName name , IBinder binder){
  mServiceMessenger = new Messenger(binder)
  Message msg = Message.obtain()
  mServiceMessenger.send(msg)
}
  1. The above message will be sent to the handler that we have defined in a separate process for handling.

Sending the message from Activity to service and Back in both directions

Somehow we need a way to send messages back to the activity. This is achieved using the property of the message called message.replyTo() which helps us send messengers attached to messages.

  1. Create a handler for our activity.
  2. Then create a Messenger using the handler.
  3. Then send that messenger to the service using the message.
mActivityMessenger = new Messenger(Handler())
Message msg = Message.obtain()
msg.replyTo = mActivityMessenger
mServiceMessenger.send(msg)