第十章 IntentService

一、IntentService是什么

IntentService是是service子类,比普通的Service增加了处理耗时任务的功能

二、IntentService使用方法

1.创建IntentService实例

   private class MyIntentService extends IntentService {

        public MyIntentService() {
            super("MyIntentService");
        }

        @Override
        protected void onHandleIntent(@Nullable Intent intent) {

        }
    }

2.运行IntentService

   Intent intent = new Intent(this, MyIntentService.class);
   startService(intent);

三、IntentService机制原理

在onCreate中创建了线程

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

onStart中将新添加的Intent 加入消息队列中

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

四、IntentService和Service的区别

  • IntentService使用队列来管理Intent请求
  • IntentService会创建单独的worker线程来处理所有的Intent请求,在OnHandleIntent()方法中实现。
  • IntentService处理完所有请求后会自动停止,开发者无须调用stopSelf();
  • IntentService默认实现了onBind()方法,但返回为null
  • IntentService默认实现了onstartCommand(),该方法将请求的Intent添加到队列中

你可能感兴趣的:(第十章 IntentService)