单个ServiceConnection
实例可用于绑定到多个服务。
在ServiceConnection.onServiceConnected()
中,您必须检查绑定了哪个服务(使用className.getClassName()
or className.getPackageName()
)并将其放在适当的字段/变量等中。
我使用这个线程作为参考,虽然我修改它以满足我的需要。
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;
}
}
}