Android Service學習之IntentService 深入分析

來源:互聯網
上載者:User

什麼是IntentService? (本文轉自http://blog.csdn.net/gaojie314/archive/2010/11/28/6040701.aspx

官方的解釋是:IntentService is a base class for Service
s that handle asynchronous requests (expressed as Intent
s) on demand. Clients send requests through android.content.Context.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.

意思是說:IntentService是一個通過Context.startService(Intent)
啟動可以處理非同步請求的Service,使用時你只需要繼承IntentService和重寫其中的onHandleIntent(Intent)
方法接收一個Intent對象,在適當的時候會停止自己(一般在工作完成的時候). 所有的請求的處理都在一個背景工作執行緒中完成,它們會交替執行(但不會阻塞主線程的執行),一次只能執行一個請求.(**本人修改了原文的一些翻譯)下面是要分析的源碼:public
abstract
class
IntentService extends
Service {

        private
volatile
Looper mServiceLooper;

        private
volatile
ServiceHandler mServiceHandler;

        private
String mName;

        private
boolean
mRedelivery;

    

        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 實際上是Looper,Handler,Service 的集合體,他不僅有服務的功能,還有處理和迴圈訊息的功能.

下面是onCreate()的源碼:        @Override

        public
void
onCreate() {

                super
.onCreate();

                HandlerThread thread = new
HandlerThread("IntentService["
+ mName + "]"
);

                thread.start();

                mServiceLooper = thread.getLooper();

                mServiceHandler = new
ServiceHandler(mServiceLooper);

        }

分析:IntentService建立時就會建立Handler線程(HandlerThread)並且啟動,然後再得到當前線程的Looper對象來初始化IntentService的mServiceLooper,接著建立mServicehandler對象.下面是onStart()的源碼:        @Override

        public
void
onStart(Intent intent, int
startId) {

                Message msg = mServiceHandler.obtainMessage();

                msg.arg1 = startId;

                msg.obj = intent;

                mServiceHandler.sendMessage(msg);

        }

分析:當你啟動IntentService的時候,就會產生一條附帶startId和Intent的
Message並發送到MessageQueue中,接下來Looper發現MessageQueue中有Message的時候,就會停止Handler
處理訊息,接下來處理的代碼如下:

        @Override

        public
void
handleMessage(Message msg) {

                        onHandleIntent((Intent)msg.obj);

                        stopSelf(msg.arg1);

        }

接著調用 onHandleIntent((Intent)msg.obj),這是一個抽象的方法,其實就是我們要重寫實現的方法,我們可以在這個方法裡面處理我們的工作.當任務完成時就會調用stopSelf(msg.arg1)這個方法來結束指定的工作.

當所有的工作執行完後:就會執行onDestroy方法,源碼如下:

        @Override

        public
void
onDestroy() {

                mServiceLooper.quit();

        }

服務結束後調用這個方法 mServiceLooper.quit()使looper停下來.

通過對源碼的分析得出:
 
 
這是一個基於訊息的服務,每次啟動該服務並不是馬上處理你的工作,而是首先會建立對應的Looper,Handler並且在MessageQueue中添
加的附帶客戶Intent的Message對象,當Looper發現有Message的時候接著得到Intent對象通過在
onHandleIntent((Intent)msg.obj)中調用你的處理常式.處理完後即會停止自己的服務.意思是Intent的生命週期跟你的
處理的任務是一致的.所以這個類用下載任務中非常好,下載任務結束後服務自身就會結束退出.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.