1

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

4

1 回答 1

1

据我了解,在此之后,服务被破坏

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

于 2015-02-07T16:39:52.843 回答