I have several Android Service
s that I want to bind to in my Activity
, so I can monitor several actions from the user.
To be able to bind every Service, and I will have several, do I need several private ServiceConnection
s in my activity like the following?
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
GPSLocalBinder gpsBinder = (GPSLocalBinder) service;
PhotoLocalBinder photoBinder = (PhotoLocalBinder) service;
gpsService = gpsBinder.getService();
photoService = photoBinder.getService();
mGpsBound = true;
mPhotoBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mGpsBound = false;
mPhotoBound = false;
}
};
Or do I need a manager class between my Activity and the Services that provides better usage and understanding of the bounded Services?
A single
ServiceConnection
instance can be used for binding to multiple Services.In
ServiceConnection.onServiceConnected()
, you'd have to check which service was bound (usingclassName.getClassName()
orclassName.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.
I assume you're asking if you can reuse the same
serviceConnection
for multiple services. There's no need to have one for each service connection, but this is probably the best approach. I see in your code thisThis is very confusing... this seems like a service can be cast into two different services!!
You'll realize that the
onServiceConnected
callback is where most of the magic happens, where you (the Activity) finally can get a pointer to your Service and start calling methods and interact with your service. If you want to reuse the sameserviceConnection
for different services you'd need to find out which custom subclass the IBinder object belongs to and then cast appropriately. Ufff, too much trouble. I would recommend having oneserviceConnection
per service.For both this and your first question, you can do whatever you want. There's no approach better than the other (IMHO) and the best one is the one you understand better and makes you feel more comfortable.