能否将一个服务绑定到另一个服务?

16

我想知道是否可以从另一个服务绑定一个服务。例如,当前我有一个活动A启动了一个服务B,现在我只想让服务B绑定并启动另一个服务C。那么有人知道如何做到这一点吗?也就是说,我可以使用与活动A启动服务相同的方法来启动一个服务,并用该服务启动另一个服务吗?

2个回答

28

您可以像从Activity中一样从Service中调用bindService。从javadoc中可以看出,唯一无法调用bindService的地方是在BroadcastReceiver中。您也可以使用ServiceConnection来接收Binder


你能指导我找到一份教程吗?帮助我开始在Android中进行服务间通信...谢谢。 - John x
2
这是使用的好方法吗?如果原始“Service”调用了“startForeground”,那么第二个“Service”也会在后台运行吗? - StuStirling

4

这对我来说是有效的。如果我从onCreate中调用bindService,那么onServiceConnected与第一次调用onHandleIntent同时发生竞争,因此如果它太快地到达,请重新提交intent。我的代码大致如下:

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();
  } 

1
你可以使用Service。 - Ishaan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接