I have an android service, which is connected to a service connection. Upon initialization, I'd like to send a single String, for example "test message" to the Service connection. How would I do this?
This is my Service class:
public class ExampleService extends Service {
private final IBinder iBinder = new Messenger(new IncomingHandler(this)).getBinder();
@Override
public IBinder onBind(Intent intent) {
return iBinder;
}
}
This is my ServiceConnection implementation:
private ServiceConnection myService = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
Log.i("exampleService", "Binding Connect");
messenger = new Messenger(iBinder);
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
messenger = null;
}
};
The
ServiceConnectionmonitors the state of the connection to the service, as opposed to communicating information to the service. To communicate with the service, you need to use thebinderthat is passed as an argument to theonServiceConnected(ComponentName name, IBinder binder)callback.In your code sample, you are using a
Messengerto perform communication instead of directly interacting with the binder. AMessengeris:Sample code that does what you are asking:
For a more detailed example of how to work with
Messenger, see the Remote Messenger Service Sample.A couple notes:
Binderthat has a method which returns the instance of the service. See the Local Service Sample for an example.bindService(...)has a correspondingunbindService(...)and vice versa. For example, if you callbindService(...)inonCreate(), then callunbindService(...)inonDestroy().IBinderinstances may stay in memory beyond the lifecycle of the component that is containing it, potentially until the process is destroyed; this can cause a severe memory leak. If you subclassBinderinside of an Activity or Service class, then use a static inner class, as opposed to a non-static inner class which will have an implicit reference to the Service or Activity. If you need a reference to a context or lifecycle aware component, then use a WeakReference. The proper way to deal with this is outside the scope of this question. For related posts, see: