2011-10-12 49 views
2

我一直在尋找一些方法來獲取ServiceConnection,當我啓動我的服務使用startService(...)。使用startService啓動服務時,如何獲得IBinder/ServiceConnection/onServiceConnected?

我還沒有找到一種方法,所以我一直在尋找了一下,發現這樣的: Does each Activity need to Bind to a Service & What happens when it was created with startService()

在那裏,Commonsware說,如果我的startService調用之後調用bindService它並不重要。

所以我想我先運行startService(...),然後直接執行bindService(...)(以便調用onServiceConnected)。但是,然後Service.onCreate執行兩次。可能是因爲startService沒有「完成」呢?

問題是:如何獲得對我的服務(IBinder)的引用,即。如果我使用startService啓動我的服務,如何獲得onServiceConnected來激發?

---編輯---

我還是想知道的任何答案,你可能有想法。我做了一個「黑客」來解決這個問題:

我只是做了一個靜態引用(SRef.java我有公共靜態的IBinder myBinder = NULL),在我Service.onCreate我簡單做

序列S .myBinder = myBinder;

這似乎不適合我,所以任何其他想法如何它應該工作將不勝感激。

回答

0

我使用完全相同的技術(一個桑巴客戶端服務),onCreate永遠不會被調用兩次,我得到的binder(通過連接回調),如我所料。新的活動開始不會觸發onCreate,因爲之前的startService已經執行了服務的啓動。

這裏是我的代碼(可能是微不足道的,但也許它可以幫助):

活動(onCreate):

startService(new Intent(this, SambaService.class)); 
bindService(new Intent(this, SambaService.class), sambaServiceConnection, 
     Context.BIND_AUTO_CREATE); 

服務:

private ServiceBinder mServiceBinder = new ServiceBinder(); 

public class ServiceBinder extends Binder { 
    public SambaService getService() { 
     return SambaService.this; 
    } 
} 

public IBinder onBind(Intent intent) { 
    return mServiceBinder; 
} 
+0

感謝。我做了startService和bindSerbie,但onCreate確實執行了兩次。奇怪的。我必須在某個時候再試一次。現在,我正在使用靜態變量,如編輯中所述。 – Ted

相關問題