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?
Is there a need to have one serviceConnection for each android service?
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 this
GPSLocalBinder gpsBinder = (GPSLocalBinder) service;
PhotoLocalBinder photoBinder = (PhotoLocalBinder) service;
gpsService = gpsBinder.getService();
photoService = photoBinder.getService();
This 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 same serviceConnection
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 one serviceConnection
per service.
Or do i need a manager class between my activity and the services that provides better usage and understanding of the bounded services?
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.