2012-02-17 36 views
3

我正在處理一個項目,需要一個活動來連接到本地服務,如果該服務正在運行,並啓動它,如果它沒有運行。 什麼是適合這種方法的標誌。綁定到服務,如果存在

+2

哈哈,對這個問題的編輯完全顛倒了它的意思。 GJ傢伙。 – Jens 2012-02-17 13:00:05

回答

5

這可以簡單地通過例如將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