Android必读之IntentService

IntentService是继承并处理异步请求的一个类,在IntentService内有一个工作线程来处理耗时操作,启动IntentService的方式和启动传统的Service一样,同时,当任务执行完后,IntentService会自动停止,而不需要我们手动去控制或stopSelf()。另外,可以启动IntentService多次,而每一个耗时操作会以工作队列的方式在IntentService的onHandleIntent回调方法中执行,并且,每次只会执行一个工作线程,执行完第一个再执行第二个,以此类推。
先来看一下IntentService类的源码:

  1. 在onCreate方法中新建一个HandlerThead和一个ServiceHandler
    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);
     }

     

  2. 我们看一下ServiceHandler的实现源码
        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);
            }
        }

    我们可以看到handlermessage方法,ServiceHandler接受到消息后进行处理我们自己实现的onHandlerIntent方法,处理完成之后立即调用Service本身的stopSelft方法来停止Service

  3. 看一下ServiceHandler什么时候会接收到message
        @Override
        public void onStart(@Nullable Intent intent, int startId) {
            Message msg = mServiceHandler.obtainMessage();
            msg.arg1 = startId;
            msg.obj = intent;
            mServiceHandler.sendMessage(msg);
        }
        @Override
        public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
            onStart(intent, startId);
            return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
        }

    很明显,当Service创建成功后会立即向ServiceHandler发送Message

自定义一个Intent Service:

package com.horry.intentservice;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
public class MyIntentService extends IntentService {
    /**
     * 默认无参构造函数
     */
    public MyIntentService() {
        super("MyIntentService");
    }
    public MyIntentService(String name) {
        super(name);
    }
    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d("MyIntentService", "开始处理耗时操作");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Log.d("MyIntentService", "耗时操作处理完成");
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("MyIntentService", "Service自动停止");
    }
}

启动之:

class MainActivity : AppCompatActivity() {//kotlin
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        startService(Intent(this, MyIntentService::class.java))
    }
}

日志:

D/MyIntentService: 开始处理耗时操作
D/MyIntentService: 耗时操作处理完成
D/MyIntentService: Service自动停止

源码:https://github.com/GoToFly/Intent-ServiceDemo

点赞

发表评论