2016-08-19 122 views
0

什麼時候服務的onStartCommand被正確執行?什麼時候執行服務的onStartCommand

在下面的代碼我的服務是從的onCreate在我的活動開始

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     Intent intent = new Intent(this, CenseDroidService.class); 
     //onStartCommand is not extecuted immediatly after startService 
     startService(intent); 
     bindService(intent, mConnection, Context.BIND_AUTO_CREATE); 
    } 

所以當它的Android系統決定調用onStartCommand?我所知道的是,在調用startService之後的一段時間,它在主線程上運行。 onCreate在onStartCommand被調用之前完全執行。

回答

0

documentation

通過系統每次都被叫客戶明確調用startService(意向),只要它提供的參數和一個唯一的整數憑證,代表啓動請求

這句話的意思是啓動服務,每當您用Intent撥打startService(intent),就會調用onStartCommand。如果您有一百項活動都需要啓動並綁定到此服務,那麼他們將全部呼叫startService()onStartCommand將被調用。

現在當它是剛好調用是有點棘手的答案。這是在未來的某個時間,這就是爲什麼你的ServiceConnection異步工作。它很可能在下一個UI線程週期內,但它不是你應該依賴的。

如果您需要關於Service何時開始的合理知識,則可以使用LocalBroadcastManager將事件廣播給所有註冊的偵聽器。 LocalBroadcastManager#sendBroadcastSync實際上會阻止,直到所有聽衆都響應,因此可能對這種情況有用。