IntentService and HandlerThread count



正如文档所说,我正在努力理解intetService是如何在单个后台线程中完成所有工作的。所以我深入研究源代码,并有一个问题

    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队列中
但假设服务接收到多个意向,并将所有意向添加到队列中。但在处理第一条消息后,handleMessage中onHandleIntent之后的下一个调用是stopSelf(消息arg1)。据我所知,在这之后,服务被破坏,但HandlerThread继续处理消息。在摧毁之后,假设我再发送一个意向服务。由于意图服务被破坏,此调用onCreate并创建另一个HandlerThread,在那之后就没有了几个Worker线程,不像文档中所说的Single。有人能解释一下我错在哪里吗?

据我所知,在这之后,的服务被破坏了

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

相关内容

  • 没有找到相关文章

最新更新