I am new to android,
I must write a service (on a different process) to handle my internet communication functions,
I checked a few blogs, and found out that using messengers we can communicate between an activity and a service (on a different process),
My question is here, So far I’m doing something like this:
private Messenger _commandReceiver = new Messenger(new CommandDispatcher());
public IBinder onBind(Intent intent) {
return _commandReceiver.getBinder();
}
class CommandDispatcher extends Handler {
public void handleMessage(Message message) {
int command = data.getInt("command");
Messenger activityMessenger = (Messenger) data.get("messenger");
switch (command) {
case Command.IS_AUTHENTICATED:
break;
...
}
}
}
But why shouldn’t I send the command variable and activity messenger on the onBind method and handle the whole event there, that way the service messenger can be totally removed and communication code is way simpler,
It would become like this
public IBinder onBind(Intent intent) {
Bundle data = intent.getExtras();
int command = data.getInt("command");
Messenger activityMessenger = (Messenger) data.get("messenger");
switch (command) {
case Command.IS_AUTHENTICATED:
break;
...
}
}
I know it might be very simple question, but I couldn’t find the answer anywhere, So I would be thankful if anyone could help me with it
Extending the Binder class
If your service is private to your own application and runs in the same process as the client (which is common), you should create your interface by extending the Binder class and returning an instance of it from onBind(). The client receives the Binder and can use it to directly access public methods available in either the Binder implementation or even the Service.
This is the preferred technique when your service is merely a background worker for your own application. The only reason you would not create your interface this way is because your service is used by other applications or across separate processes.
Using a Messenger
If you need your interface to work across different processes, you can create an interface for the service with a Messenger. In this manner, the service defines a Handler that responds to different types of Message objects. This Handler is the basis for a Messenger that can then share an IBinder with the client, allowing the client to send commands to the service using Message objects. Additionally, the client can define a Messenger of its own so the service can send messages back.
http://developer.android.com/guide/components/bound-services.html