Inentserviceソース分析


概要
前にHandlerThreadのソースコードを分析して、以下に順にIntentServiceのソースコードを分析して、IntentServiceは自分で1つのスレッドを維持して、時間のかかる操作を実行して、それから中にHandlerThreadをカプセル化して、サブスレッドでHandlerを作成するのが便利です.
本文
コメント

IntentService is a base class for {@link Service}s that handle asynchronous
requests (expressed as {@link Intent}s) on demand.  Clients send requests
through {@link 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.

InentServiceは、非同期要求を処理するためにServiceから継承されたベースクラスであり、クライアントstartServiceが要求を送信すると、InentServiceが起動され、渡されたIntentがワークスレッドで処理され、タスクが終了すると自動的にサービスが停止します.

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 {@link #onHandleIntent(Intent)}.  IntentService
will receive the Intents, launch a worker thread, and stop the service as appropriate

ワークベンチ処理モードは、通常、プライマリ・スレッドを適用する時間のかかるタスクをロードするために使用され、IntentServiceは、このモードを簡略化し、時間のかかるタスクの処理に専念するために使用されます.IntentServiceを使用するには、IntentServiceを継承し、onHandleIntentメソッドを複写する必要があります.IntentServiceは、一連のIntentを受信した後、サブスレッドを起動し、適切に実際にServiceを閉じます.

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.

すべてのリクエストは同じサブスレッドで処理されます.アプリケーションのloopスレッドをブロックすることはありませんが、IntentServiceは同じ時点で1つのリクエストしか処理できません.
注釈を通じて、すでにIntentServiceの使用方式を、シーンの説明を使ってかなりはっきりしていて、多く説明しないで、私達自身がIntentの中でスレッドを開いて時間のかかる任務を処理することに比べて、IntentServiceは私達自身がサービスを閉じる必要はなくて、それは自分で任務が完成した後に自分で閉じることができて、しかし毎回1つの任務しか処理できないので、高い同時性に適用しないで、要求数の少ない情況に適用します.APPのバージョン検出更新、バックグラウンド位置決め機能、および少量のIO操作の読み取りと同様です.
メンバー変数

    private volatile Looper mServiceLooper;//     Looper
    private volatile ServiceHandler mServiceHandler;//       Handler
    private String mName;//         
    private boolean mRedelivery;//              onStartCommand    Intent

ServiceHandler

  private final class ServiceHandler extends Handler {
        public ServiceHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
          //      Intent
            onHandleIntent((Intent)msg.obj);
            stopSelf(msg.arg1);
        }
    }

内部にServiceHandlerが作成され、渡されたIntentをMessageにカプセル化し、MessageをIntentにカプセル化し、onHandleIntentにコールバックします.実は変換の目的は、メインスレッドのIntentをサブスレッドに切り替えて実行することです.
構築方法

  //       
  public IntentService(String name) {
        super();
        mName = name;
    }

onCreate

    @Override
    public void onCreate() {
        super.onCreate();
        //  HandlerThread   
        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
        //         Looper
        thread.start();
        //     Looper
        mServiceLooper = thread.getLooper();
       //     Handler
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }

onStartCommand

  @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        //  onStart  
        onStart(intent, startId);
       //  mRedelivery         Intent            
        return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
    }

onStart

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


   @Override
        public void handleMessage(Message msg) {
            //         ,    
            onHandleIntent((Intent)msg.obj);
           //         Service
            stopSelf(msg.arg1);
        }

onDestroy

    @Override
    public void onDestroy() {
       //  Looper
        mServiceLooper.quit();
    }

使用方法

IntentService intentService = new IntentService("main") {
    @Override
    protected void onHandleIntent(Intent intent) {
        //       
    }
};
//     Service     ,IntentService     

まとめ
IntentServiceは実際に内部でHandlerThreadをインスタンス化し、Handlerをカプセル化しているので、彼のワークフローは上のソースコードを通じて、以下のように分析されています.
  • HandlerThreadを作成し、HandlerThreadを開いてLooper
  • を作成します.
  • は、Looperに入力されるHandlerを作成し、それによって、サブスレッドでHandler
  • をインスタンス化する
  • onStartCommandで取得したIntentメッセージのobjは
  • に送信される.
  • はその後、onHandleIntentでこのメッセージを処理し、サブスレッド
  • であることに注意する.
  • はHandlerThreadと同様にInentService内部ではHandlerを採用して実現されるため、タスクはシリアルで実行され、大量の時間のかかる操作には適用されません.