-
Notifications
You must be signed in to change notification settings - Fork 0
Using a seperate process
Devrath edited this page Apr 16, 2024
·
5 revisions
- We mark the service to be run in a
separate processas below
<service android:name=".service.PlayerService"
android:process=":playerprocess"/>By the below way, a messenger can be passed between the Activity and Service as a binder.
- Return
messengerreference instead ofIBinderreference - A
messengeris just a reference to a handler. - Basically when you create a
messengerwe pass ahandlerduring the creation. - A
messengercan be transformed into abinder. - A
messengercan be created from abinder.
- Create a
Handlerto handle the messages to be sent intoService. - Then create a new
messengerobject in theservice. - Next pass the
handlerreference into theserviceclass - Then we return the
messengerasbinderin theonBindmethod.
Service
mMessenger = Messenger(handler)
onBind(){
return mMessenger.getBinder()
}- Now we can recreate the
messengerin theonServiceConnected()method using theiBinderreference. - We can now create a message object and pass the
messageto themessengerActivity
onServiceConnected(ComponentName name , IBinder binder){
mServiceMessenger = new Messenger(binder)
Message msg = Message.obtain()
mServiceMessenger.send(msg)
}- The above message will be sent to the handler that we have defined in a separate process for handling.
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.
- Create a
handlerfor ouractivity. - Then create a
Messengerusing thehandler. - Then send that
messengerto theserviceusing themessage.
mActivityMessenger = new Messenger(Handler())
Message msg = Message.obtain()
msg.replyTo = mActivityMessenger
mServiceMessenger.send(msg)