I just want to know could I bind a service from another service. For example, currently I have an activity A
starting a service B
and now I just want service B
to bind and start another service C
. So does anybody know how to do that? That means could I use the same method for activity A
to start a service on a service to start another service?
You can call bindService from a Service exactly the same way you can call it from an Activity. You'll notice from the javadoc that the only place you can't call bindService is in a BroadcastReceiver . You can use a ServiceConnection as well to receive the Binder .
As discussed in the Services document, you can create a service that is both started and bound. That is, you can start a service by calling startService() , which allows the service to run indefinitely, and you can also allow a client to bind to the service by calling bindService() .
A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.
Started services run until they are stopped or destroyed and do not inherently provide a mechanism for interaction or data exchange with other components. Bound services, on the other hand, provide a communication interface to other client components and generally run until the last client unbinds from the service.
You can call bindService
from a Service exactly the same way you can call it from an Activity. You'll notice from the javadoc that the only place you can't call bindService
is in a BroadcastReceiver
. You can use a ServiceConnection
as well to receive the Binder
.
This works for me. If I call bindService
from onCreate
then onServiceConnected
is in a race with the first call to onHandleIntent
, so re-submit the intent if it arrives too soon. My code is roughly like this.
class MyService extends IntentService implements ServiceConnection {
IMyOtherService iService;
@Override
void onCreate() {
bindService(intent);
}
@Override
void onServiceConnected(ComponentName name, IBinder service) {
iService = IMyService.Stub.asInterface(service);
}
@Override
void onHandleIntent(Intent intent) {
if (iService == null) {
/* onHandleIntent has lost the race with onServiceConnected
* so wait 250 ms and resend the Intent.
*/
try { System.getCurrentThread().sleep(250); } catch (InterruptedException e) { }
startService(intent);
}
iService->method1();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With