绑定到服务,如果存在

问题描述:

我正在处理一个项目,需要一个活动来连接到本地服务,如果该服务正在运行,并启动它,如果它没有运行。 什么是适合这种方法的标志。绑定到服务,如果存在

+2

哈哈,对这个问题的编辑完全颠倒了它的意思。 GJ家伙。 – Jens 2012-02-17 13:00:05

这可以简单地通过例如将0的最后一个参数传递给#bindService(Intent, ServiceConnection, int)来完成。

E.g.

bindService(new Intent(this, MrMeService.class), new ServiceConnection(){ 
     public void onServiceDisconnected(ComponentName name) { 
      System.out.println("Service disconnected"); 
     } 
     public void onServiceConnected(ComponentName name, IBinder service) { 
      System.out.println("Service connected"); 
     } 
    }, 0); 

#bindService(..)调用将返回true但该服务将真正开始,你的服务连接不会触发直到有人真正开始服务,例如使用#startService(Intent)。至少这是它在ICS和姜饼上的工作原理。

+0

在标志列表中没有看到0,谢谢 – 2012-02-17 13:07:17

+0

这是一个很好的答案,因为许多其他人只建议存储由bindService()方法返回的布尔值,而这不正确。这是对的。注意:unbindService()不会调用onServiceDisconnected(),即使它从服务中解除绑定。 (),> onBause() - > unbind(),onEventToStart() - > start(),onEventToStop() - > stop()。 在我测试过的所有设备上工作。 – Armando 2013-05-30 21:51:45