美文网首页
Android中的线程形态-IntentService

Android中的线程形态-IntentService

作者: hiandg | 来源:发表于2017-11-19 23:26 被阅读0次
    • IntentService 可用于执行后台耗时的任务,当任务执行完时它会自动停止。IntentService比较适合执行一些优先级高的后台任务。它封装ThreadHandler和Handler

    第一次启动IntentService的时候会调用onCreate(),onCreate方法会创建一个HandlerThread然后通过一个Looper来构造一个Handler对象。这样通过mServiceHandler 发送的消息最终都会在HandlerThread中执行。每次启动IntentService,它的onStartCommand方法就会被调用一次,IntentService在onStartCommand中处理每个后台任务的Intent。每个onStarCommand会调用onStart

        @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);
        }
    
    /**
         * 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(@Nullable Intent intent, int flags, int startId) {
            onStart(intent, startId);
            return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
        }
    

    IntentService仅仅是通过mServiceHandler发送了一个消息,这个消息会在HandlerThread中被处理。mServiceHandler收到消息后,会将Intent对象传递给onHandlerIntent方法处理。

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

    stopSelf(int startID):会等所有消息都处理完后在终止服务。在终止之前需要判断最近启动服务的次数是否和startId相等。onHandleIntent()执行完最后一个任务的时候,stopSelf(int startId)才会停止服务。当有多个后台任务同时存在时,后台任务会按照外界发起的顺序排队执行。

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

    相关文章

      网友评论

          本文标题:Android中的线程形态-IntentService

          本文链接:https://www.haomeiwen.com/subject/vpnpvxtx.html