因此,我正在爲一個學校項目開發Android應用程序,並且在開發結束時遇到了一個奇怪的錯誤。應用程序的一部分是一個服務,它在後臺運行,並經常與服務器簽入,但需要選擇是在後臺運行服務還是使用手動簽入。爲了避免重複代碼,我試圖做的是將一個Intent沿着「強制更新一次,然後停止」的布爾值開始傳遞給服務。但是,我的服務似乎沒有得到這個價值。如何在啓動時將意圖傳遞給服務(但僅在某些情況下)
啓動該服務的代碼:
Intent intent = new Intent(this, EmpCheckinService.class);
intent.putExtra("singleCheckInOnly", true);
intent.putExtra("locationString", location);
startService(intent);
而在服務類中的代碼:
// This is the old onStart method that will be called on the pre-2.0
// platform. On 2.0 or later we override onStartCommand() so this
// method will not be called.
@Override
public void onStart(Intent intent, int startId) {
examineIntent(intent);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
examineIntent(intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
private void examineIntent(Intent intent) {
try {
singleCheckInOnly = intent.getExtras().getBoolean("singleCheckInOnly", false);
locationString = intent.getExtras().getString("locationString");
} catch (Exception e) {
// Don't need to do anything here, just prevent from crashing if the keys aren't found
}
}
正如你所看到的,我有在onStart和onStartCommand目前它允許在1.5或2.1+以上的設備上工作,但它從來沒有達到這些功能之一。任何人都可以在這裏指出我正確的方向嗎?
編輯:我想我找到了問題。 OnCreate是否在onStartCommand之前調用?
你說它似乎沒有得到這個值,這是否意味着系統在檢索時崩潰('singleCheckInOnly = intent.getExtras()。getBoolean(「singleCheckInOnly」,false)')? – pecka85 2011-04-14 17:38:09
不,我在每個函數的開頭都有斷點,調試器從不碰它們,但直接進入服務的其餘部分 – zachtib 2011-04-14 17:52:02