The Service is bound to the Android Component. The communication methods are generally as follows:
1. Return the Binder object in onBind (Intent intent). Use this interface to interact with the Service.
2. Create a Messenger through the IBinder object and interact with the Service through Handler
3. interaction through AIDL
The first method to return the Binder is the most convenient, because the Service instance can be directly returned in the Binder, so that Component can directly communicate with the Service.
However, there is a limitation that the Service and Component can only be carried out in the same process through the Binder method. If this Service is used internally by a program, this is the preferred communication method.
Note that when multiple components are bound to the same Service, the system only calls the onBind method when the first Component is bound, when other components are bound, the first returned Binder is directly returned, that is, multiple components use the same Binder.
If you attempt to return a Binder between different processes, the system reports an error during running.
The second is to interact with each other through a Messenger. the creation and use of Messenger are simple as follows:
// In Service
@ Override
Public IBinder onBind (Intent arg0 ){
Return mmesder. getBinder ();
}
Private Messenger mMessenger = new Messenger (new HelloHandler ());
Class HelloHandler extends Handler {
@ Override
Public void handleMessage (Message msg ){
Toast. makeText (getApplicationContext (), "Hello", Toast. LENGTH_SHORT). show ();
Super. handleMessage (msg );
}
}
// In Activity
Private Messenger mMessenger;
Private ServiceConnection SC = new ServiceConnection (){
Public void onServiceConnected (ComponentName name, IBinder service ){
Log. I (TAG, "service connection ");
MMessenger = new Messenger (service );
MBound = true;
}
Public void onServiceDisconnected (ComponentName name ){
Log. I (TAG, "disconnect service ");
MBound = false;
}
};
In this way, you can communicate with the Service by sending messages. The advantage of Messenger is that it can communicate with Compontent when the Service and Compontent are in different processes, this is not possible with the Binder method. The underlying layer of Messenger is implemented with AIDL.
In general, the first two can meet the needs of most programs, if you want to do the Service of concurrent processing, then use AIDL to achieve, see the specific http://developer.android.com/guide/developing/tools/aidl.html
Component
Author da Xiaosheng