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 co开发者_JAVA技巧uld 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
.
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();
}
精彩评论