因為大多被啟動類型的服務不需要同時處理多個請求(這實際是一個危險的多線程情境),因此使用IntentService類來實現自己的服務可能是最好的。
IntentService類執行以下操作:
1. 建立一個獨立與應用程式主線程的預設背景工作執行緒,執行所有的給onStartCommand()方法Intent的處理;
2. 建立一個工作隊列,以便每次只給你的onHandleIntent()方法實現傳遞一個Intent,因此你不必擔心多線程的問題;
3. 所有的啟動請求都被處理之後終止這個服務,因此你不需要自己去調用stopSelf()方法;
4. 提供返回null的onBind()方法的預設實現;
5. 提供一個給工作隊列發送Intent對象的onStartCommand()方法的預設實現和onHandleIntent()方法的實現。
所以這些加起來實際上只需要實現onHandleIntent()方法,來完成由客戶提供的工作(雖然,你還需要給服務提供一個小的構造器)。
例如:
public class HelloIntentService extends IntentService {
/**
* A constructor is required, and must call the super
IntentService(String)
* constructor with a name for the worker thread.
*/
public HelloIntentService() {
super("HelloIntentService");
}
/**
* The IntentService calls this method from the default worker thread with
* the intent that started the service. When this method returns, IntentService
* stops the service, as appropriate.
*/
@Override
protected void onHandleIntent(Intent intent) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
long endTime = System.currentTimeMillis() + 5*1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
wait(endTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
}
}
以上就是你做的全部:一個構造器和一個onHandleIntent()方法的實現。
如果你還決定要重寫其他的回調方法,如onCreate()、onStartCommand()、或onDestroy(),那麼就要確保調用父類的實現,以便IntentService對象能夠適當的處理背景工作執行緒的活動。
例如,onStartCommand()方法必須返回預設的實現(預設的實現擷取Intent並把它交付給onHandleIntent()方法):
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent,flags,startId);
}
除了onHandleIntent()方法以外,唯一不需要調用實現的方法是onBind()方法(但是如果你的服務允許綁定,就要實現這個方法)。