Android IntentService vs Service

來源:互聯網
上載者:User

標籤:android   intentservice   

Android IntentService vs Service

眾所周知,Android中的Service是用於後台服務的,當應用程式被掛到背景時候,為了保證應用中某些功能仍然可以工作而引入了Service,比如播放音樂。針對service,官方文檔有2點重要說明:
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). Service不是一個線程,也就是說service和UI主線程是在同一線程中啟動並執行,因此service不能執行耗時間長度的處理,防止出現ANR。
因此如果APP需要在service執行長時間處理時,需要起個獨立線程來處理該操作。
Android為我們考慮到了這一點,所以提供了IntentService類。IntentService繼承於Service,可以認為是開了一個線程來處理事件的service.
IntentService有如下優點:
1. 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. 隊列任務按序執行,全部任務結束後會結束自己。
2. 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.
3. 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.所有請求在一個背景工作執行緒中完成,但是一次之後處理一個。
下面我們對IntentService代碼進行分析:
繼承自service
public abstract class IntentService extends Service
有一個背景工作執行緒,在onCreate中建立該線程
HandlerThread thread = new HandlerThread(“IntentService[” + mName + “]”);
內部通過handler來處理startService發送的訊息事件。同樣在onCreate函數中建立thread looper和Handler
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);

而在每次調用startService時會將任務添加到隊列中

public void onStart(Intent intent, int startId) {        Message msg = mServiceHandler.obtainMessage();        msg.arg1 = startId;        msg.obj = intent;        mServiceHandler.sendMessage(msg);}

Handler執行過程為:

private final class ServiceHandler extends Handler {        public ServiceHandler(Looper looper) {            super(looper);        }        @Override        public void handleMessage(Message msg) {            onHandleIntent((Intent)msg.obj);            stopSelf(msg.arg1);        }}

從上面可見IntentService是按照順序來執行的,全部任務執行完成後背景工作執行緒finish。

使用如下:
在manifext.xml中添加聲明

然後在調用的地方直接使用:

public void startService() {  Intent intent = new Intent(this, XXXIntentService.class);  startService(intent); } public void stopService() {  Intent intent = new Intent(this, XXXIntentService.class);  stopService(intent); }

其中調用stopService會直接調用IntentService的onDestroy函數,當前正在執行的任務不會暫停,等該任務完成後線程關閉。如果需要立即結束任務,則可以通過設定變數來讓當前任務儘快結束。

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

Android IntentService vs Service

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.