有人可以幫助我瞭解如何正確使用Android服務或IntentService。文檔似乎本身在這裏反駁:如何使用Android服務或ServiceIntent
Caution: A service runs in the same process as the application in which it is
declared and in the main thread of that application by default. If your service
performs intensive or blocking operations while the user interacts with an
activity from the same application, the service slows down activity performance.
To avoid impacting application performance, start a new thread inside the service.
這裏
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.
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// Restore interrupt status.
Thread.currentThread().interrupt();
}
}
}
考慮到服務的整個目的或ServiceIntent是運行長在後臺運行的作業,而不影響UI那麼爲什麼在示例代碼完成的注意事項表明你不應該這樣做 - 我假設調用Thread.sleep()將導致主線程阻塞。
難道我的理解如下更正:
- 服務本身仍然運行在主應用程序線程,但沒有UI組件(活動),並會繼續即使應用程序沒有被用戶運行不像的活性,這不會
- 任何長期運行的後臺工作仍必須創建一個單獨的線程來避免阻塞主應用程序線程
- 的AsyncTask被與活動相關聯這大概會停止運行,如果應用程序沒有時間r活動應用程序(即如果用戶切換到另一個應用程序),這就是爲什麼如果任務需要繼續運行,可以使用Service或ServiceIntent。
- IntentService將在單獨的線程上將任務運行到主線程,因此不需要擔心用長任務或調用Thread.sleep()時阻塞主線程。
有我誤解與Android服務或ServiceIntents的說明些什麼呢?
太棒了 - 非常感謝我需要確認 - 您應該幫助編寫文檔。 –
@DuncanGroenewald:對不起。你必須解決[書](https://commonsware.com/Android)。 :-) – CommonsWare