A single ServiceConnection
instance can be used for binding to multiple Services.
In ServiceConnection.onServiceConnected()
, you'd have to check which service was bound (using className.getClassName()
or className.getPackageName()
) and put it in the appropriate field/variable, etc.
I used this thread as a reference, though I modified it to match my needs.
private static final int SERVICE_1_INDEX = 0;
private static final int SERVICE_2_INDEX = 1;
/** Array of the subclasses of {@link BaseService}s which have been bound */
private BaseService[] mServices;
/** ServiceConnection which handles the binding/unbinding of the services */
private MyServiceConnection mServiceConnection;
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mServiceConnection = new MyServiceConnection();
}
@Override
public void onResume() {
super.onResume();
bindServices();
}
@Override
public void onPause() {
super.onPause();
unbindServices();
}
private void bindServices() {
Intent service1Intent = new Intent(getActivity().getApplicationContext(), MyService1.class);
Intent service2Intent = new Intent(getActivity().getApplicationContext(), MyService2.class);
getContext().bindService(service1Intent, mServiceConnection, Context.BIND_AUTO_CREATE);
getContext().bindService(service2Intent, mServiceConnection, Context.BIND_AUTO_CREATE);
}
private void unbindServices() {
if (mServiceConnection != null) {
getContext().unbindService(mServiceConnection);
}
}
private class MyServiceConnection implements ServiceConnection {
public void onServiceConnected(ComponentName className, IBinder boundService ) {
Log.d("className(bound)", className.getClassName());
Log.d("className(Service1)", MyService1.class.getName());
Log.d("className(Service2)", MyService2.class.getName());
BaseService.LocalBinder binder = (BaseService.LocalBinder) boundService;
if (className.getClassName().equals(MyService1.class.getName())) {
mServices[SERVICE_1_INDEX] = binder.getService();
// call method on your service like:
// binder.getService().someMethod();
// (you may need to cast to your actual Service)
}
else {
mBaseServices[SERVICE_2_INDEX] = binder.getService();
// call method on the service like in if-block
}
}
public void onServiceDisconnected(ComponentName className) {
if (className.getClassName().equals(MyService1.class.getName())) {
mBaseServices[SERVICE_1_INDEX] = null;
}
else {
mBaseServices[SERVICE_2_INDEX] = null;
}
}
}