2011-08-01 139 views
5

这是我的理解,如果我想要一个服务即使没有任何限制运行,那么它必须首先启动startService(意图我)。在bindService之前等待启动服务

我的问题是,如果我想在启动后立即绑定到服务,下面的代码是否可以保证服务是用startService()创建的?

服务类中

的静态方法:

public static void actStart(Context ctx) { 
    Intent i = new Intent(ctx, BGService.class); 
    i.setAction(ACTION_START); 
    ctx.startService(i); 
} 

结合活性:

BGService.actionStart(getApplicationContext());  
bindService(new Intent(this, BGService.class), serviceConnection, Context.BIND_AUTO_CREATE); 
+0

我面临同样的问题。你有没有找到决定? –

+3

bindservice实际上等待startservice完成 – Paul

回答

0

我不知道你正在尝试做的,但“Context.BIND_AUTO_CREATE”创建服务然后绑定到该服务,即使它尚未启动。

现在如果你想结合,你可以使用serviceConnection的onServiceConnected()方法后立即对其进行访问:

new ServiceConnection() { 
     @Override 
     public void onServiceConnected(ComponentName className, 
       IBinder service) { 
      //put your code here... 
     } ... 
0

为了增加Bugdayci的答案,一个完整的例子如下:

 ServiceConnection myConnection = new ServiceConnection() { 
      @Override 
      public void onServiceConnected(ComponentName className, 
        IBinder service) { 
        ... your code that needs to execute on service connection  

      } 


    @Override 
    public void onServiceDisconnected(ComponentName name) { 
     ... your code that needs to execute on service disconnection 

    } 
     }; 

     Intent intent = new Intent(this, TheServiceClassName.class); 
     bindService(intent, myConnection, Context.BIND_AUTO_CREATE); 

...

没有在最后的bindService的onServiceConnected()的代码将不会执行。

相关问题