IntentService源码

原文地址IntentService源码分析

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

源码可知:

1)实际上是使用了一个 HandlerThread 来维护线程的,

2) HandleThread 中,内部已经维护一个 Looper,这里直接使用 HandlerThread 的 Looper 对象,便于在 IntentService 中去维护消息队列,

3)创建的 mServiceHandler 是属于 HandleThread 这个 WorkerThread 的。

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);
        }
    }

源码可知:

1)直接把消息交给 onHandleIntent() 方法去执行具体的业务逻辑

2)执行完成之后,立即调用 stopSelf() 方法停止自己

接下来分析start源码

@Override
 public void onStart(Intent intent, int startId) {
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = intent;
        mServiceHandler.sendMessage(msg);
  }
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
        onStart(intent, startId);
        return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
    }

源码可知

1)在 onStartCommand() 中直接调用了 onStart() 方法

2)而上面 stopSelf() 方法使用的 startId 来停止当前的此次任务服务。

3)而 Service 如果被启动多次,就会存在多个 startId ,当所有的 startId 都被停止之后,才会调用 onDestory() 自我销毁。

我们在看看HandlerThread启动之后的源码

@Override
public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }

源码可知

1)run方法里面添加了锁,这也解释了为什么多次 start 同一个 IntentService 它会顺序执行,全部执行完成之后,再自我销毁。

原文地址:https://www.cnblogs.com/anni-qianqian/p/8393037.html