標籤:android style blog http color io 使用 ar for
不知道大家有沒有和我一樣,以前做項目或者練習的時候一直都是用Service來處理後台耗時操作,卻很少注意到還有個IntentService,前段時間準備面試的時候看到了一篇關於IntentService的解釋,發現了它相對於Service來說有很多更加方便之處,今天在這裡稍微來總結下我的心得。
首先IntentService是繼承自Service的,那我們先看看Service的官方介紹,這裡列出兩點比較重要的地方:
1.A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of.
2.A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).
1.Service不是一個單獨的進程 ,它和應用程式在同一個進程中
2.Service不是一個線程,所以我們應該避免在Service裡面進行耗時的操作
有一點需要強調,如果有耗時操作在Service裡,就必須開啟一個單獨的線程來處理,這點一定要銘記在心。
IntentService相對於Service來說,有幾個非常有用的優點,首先我們看看官方文檔的說明:
IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.
This "work queue processor" pattern is commonly used to offload tasks from an application‘s main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.
All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application‘s main loop), but only one request will be processed at a time.
翻譯過來是:使用隊列的方式將請求的Intent排入佇列,然後開啟一個worker thread(線程)來處理隊列中的Intent,對於非同步startService請求,IntentService會處理完成一個之後再處理第二個,每一個請求都會在一個單獨的worker thread中處理,不會阻塞應用程式的主線程,這裡就給我們提供了一個思路,如果有耗時的操作與其在Service裡面開啟新線程還不如使用IntentService來處理耗時操作。
由於服務進程的優先順序高於後台進程, 因此如果activity需要執行耗時操作, 最好還是啟動一個service來完成. 當然, 在activity中啟動子線程完成耗時操作也可以,但是這樣做的缺點在於,一旦activity不再可見,activity所在的進程成為後台進程, 而記憶體不足時後台進程隨時都有可能被系統殺死(但是啟動service完成耗時操作會帶來資料互動的問題, 比如耗時操作需要即時更新UI控制項的狀態的話,service就不是一個好的選擇)。 基於同樣的考慮, 在BroadcastReceiver中也不應該執行耗時操作, 而應該啟動service來完成(當然, BroadcastReceiver的生命週期過於短暫, 也決定了不能在其中執行耗時操作)。
總結:IntentService是一個通過Context.startService(Intent)啟動可以處理非同步請求的Service,使用時你只需要繼承IntentService和重寫其中的onHandleIntent(Intent)方法接收一個Intent對象,在適當的時候會停止自己(一般在工作完成的時候)。所有的請求的處理都在一個背景工作執行緒中完成,它們會交替執行(但不會阻塞主線程的執行),一次只能執行一個請求。
這是一個基於訊息的服務,每次啟動該服務並不是馬上處理你的工作,而是首先會建立對應的Looper,Handler並且在MessageQueue中添加的附帶客戶Intent的Message對象,當Looper發現有Message的時候接著得到Intent對象通過在onHandleIntent((Intent)msg.obj)中調用你的處理常式,處理完後即會停止自己的服務,意思是Intent的生命週期跟你的處理的任務是一致的,所以這個類用下載任務中非常好,下載任務結束後服務自身就會結束退出。
總結IntentService的特徵有:
(1)會建立獨立的worker線程來處理所有的Intent請求;
(2)會建立獨立的worker線程來處理onHandleIntent()方法實現的代碼,無需處理多線程問題;
(3)所有請求處理完成後,IntentService會自動停止,無需調用stopSelf()方法停止Service;
轉自:http://blog.csdn.net/listening_music/article/details/7239304
Android中Service與IntentService的使用比較