美文网首页
IntentService详解和使用

IntentService详解和使用

作者: 京写 | 来源:发表于2020-08-10 09:42 被阅读0次

    1. IntentService概述

    • 它本质是一种特殊的Service,继承自Service并且本身就是一个抽象类
    • 它可以用于在后台执行耗时的异步任务,当任务完成后会自动停止
    • 它拥有较高的优先级,不易被系统杀死(继承自Service的缘故),因此比较适合执行一些高优先级的异步任务
    • 它内部通过HandlerThread和Handler实现异步操作
    • 创建IntentService时,只需实现onHandleIntent和构造方法,onHandleIntent为异步方法,可以执行耗时操作
      2. 使用方法
      新建一个类,继承自IntentService
    public class MyIntentServic  extends IntentService{
        /**
         需要实现一个无参的构造函数
         */
        private static final String TAG = "MyIntentServic";
        public MyIntentServic() {
            super(TAG);
        }
        /**
       实现onHandleIntent()方法。
         */
        @Override
        protected void onHandleIntent(Intent intent) {
           String tag=  intent.getStringExtra("tag");
            Log.e(TAG, "ag-------->"+tag);
            Log.e(TAG, "Thread.id----->"+Thread.currentThread());
            try {
                Thread.sleep(5*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
     
        }
         /**
         并且还在其他生命周期方法中打印了log日志。
         */
        @Override
        public void onCreate() {
            super.onCreate();
            Log.e(TAG, "-------->onCreate:");
        }
     
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.e(TAG, "-------->onStartCommand:");
            return super.onStartCommand(intent, flags, startId);
        }
     
        @Override
        public void onDestroy() {
            super.onDestroy();
            Log.e(TAG, "-------->onDestroy:");
        }
    }
    

    如何调用启动服务

     void startService() {
            Intent intent = new Intent(this,MyIntentServic.class);
            tag++;
            intent.putExtra("tag",tag+"");
            startService(intent);
        }
    
    点击五次,查看打印log
    打印log截图

    注:和service一样,开启五次onCreate只执行一次,可见service实例只有一个,onStartCommand执行了5次,onHandleIntent也执行了5次

    2. 源码分析

    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;
        }
     
        /**
         * Sets intent redelivery preferences.  Usually called from the constructor
         * with your preferred semantics.
         *
         * <p>If enabled is true,
         * {@link #onStartCommand(Intent, int, int)} will return
         * {@link Service#START_REDELIVER_INTENT}, so if this process dies before
         * {@link #onHandleIntent(Intent)} returns, the process will be restarted
         * and the intent redelivered.  If multiple Intents have been sent, only
         * the most recent one is guaranteed to be redelivered.
         *
         * <p>If enabled is false (the default),
         * {@link #onStartCommand(Intent, int, int)} will return
         * {@link Service#START_NOT_STICKY}, and if the process dies, the Intent
         * dies along with it.
         */
        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();
        }
     
        /**
         * Unless you provide binding for your service, you don't need to implement this
         * method, because the default implementation returns null. 
         * @see android.app.Service#onBind
         */
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
     
        /**
         * This method is invoked on the worker thread with a request to process.
         * Only one Intent is processed at a time, but the processing happens on a
         * worker thread that runs independently from other application logic.
         * So, if this code takes a long time, it will hold up other requests to
         * the same IntentService, but it will not hold up anything else.
         * When all requests have been handled, the IntentService stops itself,
         * so you should not call {@link #stopSelf}.
         *
         * @param intent The value passed to {@link
         *               android.content.Context#startService(Intent)}.
         */
        protected abstract void onHandleIntent(Intent intent);
    }
    

    在onCreate()方法中,创建了一个线程HandlerThread对象,接着启动了该线程,然后将该线程的Looper对象赋值给内部类ServiceHandler。
    ServiceHandler顾名思义,就是一个Handler,在它的handleMessage()方法中,调用了onHandleIntent((Intent)msg.obj)和stopSelf(msg.arg1)方法,而onHandleIntent((Intent)msg.obj)方法是一个抽象方法,需要用户自己实现;stopSelf(msg.arg1)方法,这不是停止Service的方法嘛!

    参考这篇文章

    相关文章

      网友评论

          本文标题:IntentService详解和使用

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