2011-06-27 57 views
10

我只想知道我可以绑定另一个服务的服务。例如,目前我有一个activity A开始service B,现在我只想service B绑定并启动另一个service C。那么有人知道如何做到这一点?这意味着我可以使用相同的方法activity A启动服务上的服务以启动另一项服务?一个服务可以绑定另一个服务

回答

21

您可以从服务中调用bindService,方法与您可以从活动中调用它的方式完全相同。你会从javadoc注意到唯一你不能拨打bindService的地方是BroadcastReceiver。您也可以使用ServiceConnection以获得Binder

+0

你能指导我一个教程,可以帮助我开始在Android的互联网服务通信开始...问候 –

+2

这是一个好习惯吗?如果最初的'Service'叫做'startForeground',第二个'Service'也会在后台运行? – StuStirling

2

这适用于我。如果我从onCreate拨打bindService,那么onServiceConnected正在与第一个电话onHandleIntent竞争,因此如果过早到达,请重新提交意图。我的代码大致是这样的。

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

您可以改为使用服务。 – Ishaan

相关问题