IntentService 和 HandlerThread 计数

IntentService and HandlerThread count

我正在尝试了解 intentService 如何在单个后台线程中完成所有工作,如文档所述。所以我深入研究了源代码,并提出了一个问题

    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);
        }
    }
    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public IntentService(String name) {
        super();
        mName = name;
    }


    public void setIntentRedelivery(boolean enabled) {
        mRedelivery = enabled;
    }
    @Override
    public void onCreate() {
        // TODO: It would be nice to have an option to hold a partial wakelock
        // during processing, and to have a static startService(Context, Intent)
        // method that would launch the service & hand off a wakelock.
        super.onCreate();
        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
        thread.start();
        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }
    @Override
    public void onStart(Intent intent, int startId) {
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = intent;
        mServiceHandler.sendMessage(msg);
    }
    /**
     * You should not override this method for your IntentService. Instead,
     * override {@link #onHandleIntent}, which the system calls when the IntentService
     * receives a start request.
     * @see android.app.Service#onStartCommand
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        onStart(intent, startId);
        return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
    }
    @Override
    public void onDestroy() {
        mServiceLooper.quit();
}

因此在 onCreate 服务中创建了一个 HandlerThread。此后,所有 onStartCommand 调用都会将消息添加到 HanlderThread 队列。
但是假设服务接收到多个意图,并将所有意图添加到队列中。但是在处理了 first 消息之后,handleMessage 中 onHandleIntent 之后的下一个调用是 stopSelf(msg.arg1);。据我了解,在此之后,服务被破坏,但 HandlerThread 继续处理消息。在销毁之后,假设我再发送一个服务意图。由于 intentservice 被销毁,这会调用 onCreate 并创建另一个 HandlerThread!!,之后就没有几个工作线程,不像文档中说的那样。 谁能解释一下我哪里错了?

As i understand, after this, service is destroyed

没有。如果您调用 stopSelf(),该服务将停止。但是,stopSelf(int) 只有在没有其他未完成的 Intents 已交付给服务时才会停止服务。