2011-04-14 44 views
1

因此,我正在爲一個學校項目開發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之前調用?

+1

你說它似乎沒有得到這個值,這是否意味着系統在檢索時崩潰('singleCheckInOnly = intent.getExtras()。getBoolean(「singleCheckInOnly」,false)')? – pecka85 2011-04-14 17:38:09

+0

不,我在每個函數的開頭都有斷點,調試器從不碰它們,但直接進入服務的其餘部分 – zachtib 2011-04-14 17:52:02

回答

1

onCreate是否在onStartCommand之前調用?

是的。

這將是顯著更簡單,更人性化,如果你:

第1步:創建一個IntentService,而不是一個Service

第2步:使用AlarmManager發送Intents到服務用於與服務器的定期檢查

然後,從服務的角度來看,基於定時器的檢查與用戶啓動的檢查沒有區別。

+0

IntentService是否可以啓動並在後臺運行?我看着他們兩個,但使用Service很大程度上是因爲這個問題,我想。 – zachtib 2011-04-14 19:27:42

+0

@zachtib:「IntentService可以啓動並保留在後臺運行嗎?」 - 不,這是設計。您的目標是讓您的服務儘可能少地運行。爲了紀念時間而在內存中存儲一​​項服務是非常浪費的,這也是用戶使用任務殺手等攻擊你的原因。如果您正在實施基於時間的輪詢,則正確的答案是使用「AlarmManager」和「IntentService」。 – CommonsWare 2011-04-14 20:08:02

0

,如果你有超過1額外的投入,那麼最好是使用束

甲苯磺酰派演員使用 -

Intent i = new Intent(sender.this,receiver.class); 
      Bundle extras = new Bundle(); 
    extras.putString("key1",element); 
    extras.putString("key1",element); 
    extras.putString("key2",element2); 
    extras.putString("key3",element3); 
    extras.putString("key4",element4); 
    ......so on 
     i.putExtras(extras); 

接收使用 -

Bundle extras2 = getIntent().getExtras(); 

      if (extras != null){ 
      final String str = extras2.getString("key1"); 
final String str = extras2.getString("key2"); 
final String str = extras2.getString("key3"); 
final String str = extras2.getString("key4"); 
final String str = extras2.getString("key5"); 
......so on 
相關問題