Android多线程:如何正确使用IntentService?

前言

 Android沿用了Java的线程模型,除了Thread外,Android还实现了AsyncTask、HandlerThread、IntentService,它们的底层实现也是线程。
 本文讲的是IntentService

相关文章阅读
AsyncTask
HandlerThread


1 使用步骤

  • ①创建IntentService子类(因为IntentService是抽象类)
class WorkerIntentService(name: String?) : IntentService(name) {
    var tag = "WorkerIntentService"
    override fun onHandleIntent(intent: Intent?) {
        val action = intent?.getStringExtra("shopping")
        Log.d(tag,"onHandleIntent:${action}")
        SystemClock.sleep(250)
    }

    override fun onCreate() {
        Log.d(tag,"onCreate")
        super.onCreate()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d(tag,"onStartCommand")
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onDestroy() {
        Log.d(tag,"onDestroy")
        super.onDestroy()
    }

}
  • ②AndroidManifest.xml中注册
  
        
            
                

                
            
        
        
    
  • ③启动
   private fun myService() {
        val intent = Intent(this,WorkerIntentService::class.java)
        val bundle = Bundle()
        bundle.putString("shopping", "go go go")
        intent.putExtras(bundle)
        startService(intent)
        val fireIntent = Intent(this,WorkerIntentService::class.java)
        val fireBundle = Bundle()
        fireBundle.putString("shopping", "fire fire fire")
        fireIntent.putExtras(fireBundle)
        startService(fireIntent)
        startService(intent)
    }

2 源码分析

IntentService是Service,因此也遵循Service的生命周期,我们可直接通过分析生命周期来了解其运行的原理。
一、从onCreate方法可以看出IntentService内部封装了HandlerThread和Handler,从这里可以看出IntentService可以用于执行后台任务

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

二、onStartCommand调用了onStart,并通过mServiceHandler发送消息。

    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        onStart(intent, startId);
        return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
    }

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

三、调用onHandleIntent方法,最后调用stopSelf停止服务。

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

四、onBind返回的是null,因此IntentService不支持bindservice

    @Override
    @Nullable
    public IBinder onBind(Intent intent) {
        return null;
    }

总结

  • IntentService是一种特殊的Service,但是不能支持bindservice。
  • 因为IntentService是服务使得它的优先级较高,所以可以用IntentService执行一些高优先级的后台任务。
  • 优先级较高因此不容易被kill。

你可能感兴趣的:(Android多线程:如何正确使用IntentService?)