2011-10-07 74 views
13

我正在嘗試創建一個將在後臺處理文件I/O的服務。更新數據的活動將綁定到服務並調用服務的方法來執行I/O。我正在使用Android文檔進行指導。Android服務從未出現過 - onStartCommand()未調用

但是,我的服務似乎並不想開始。在我的活動的onCreate()方法,我有:

Intent smsIntent = new Intent(this, SurveyManagerService.class);  
String surveyFilename = getIntent().getStringExtra("surveyFilename"); 
System.out.println(startService(smsIntent)); //testing if it starts 
SurveyManagerServiceConnection connection = new SurveyManagerServiceConnection(); 
sms = connection.getSurveyManagerService(); 

在線路3的logcat輸出ComponentInfo對象,所以它會出現該服務被創建;但是,短信爲空。此外,SurveyManagerService onStartCommand()方法似乎從來沒有被稱爲:

@Override 
public int onStartCommand(Intent intent, int flags, int startId) 
{ 
    System.out.println("starting service"); 
    Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show(); 
    openSurveyFromIntent(intent); 
    return START_REDELIVER_INTENT; 
} 

我從來沒有看到任何logcat中「啓動服務」輸出,也不敬酒出現。

<service android:name=".SurveyManagerService" android:exported="false" android:enabled="true"> 
</service> 

我失去了一些東西很明顯:

我的服務我的表現爲申報?讓我知道我應該提供哪些其他信息來診斷問題。

+0

也許你的服務反覆崩潰聲明你的服務? – Reno

+0

我該如何去測試它是否在onStartCommand()的第一行之前崩潰?謝謝。我忘了說onCreate()方法也有一個System.out.println測試,它永遠不會被調用。 – Spinner

回答

5

在服務真正開始之前,似乎是onCreate()方法has to exit。一旦我刪除了getSurveyManagerService()請求,並且一旦有一段時間過去,我收到System.out消息,指示服務正在啓動。

不幸的是,這產生了另一個問題:Activity依賴於服務來處理它的數據,所以我需要確定如何使Activity等待服務啓動。

編輯:我的解決方案是在我的Activity中創建ServiceConnection的私有子類。然後,我重寫onServiceConnected()方法來爲Activity提供其數據(在這種情況下填充ListView)。

18

也許你不小心將服務標籤放在應用程序標籤之外?然後服務只是默默地失敗。儘管日誌中應該有一個「無法啓動服務意圖...」錯誤。

+0

非常感謝,但''標籤絕對在''標籤內。 – Spinner

+0

我忘了在manifest中定義一個Service標籤。謝謝 –

14

確保在AndroidManifest.xml

<application> 
    ... 
    <service android:name=".path.to.service.MyService"/> 
</application> 
相關問題