IntentService是什么?
IntentService是继承并处理异步请求的一个类,在IntentService内有一个工作线程来处理耗时操作,启动IntentService方法和启动传统的Service一样,同时,当任务执行完后,IntentService会自动停止,而不需要我们手动的stopSelf()。另外,可以启动IntentService多次,而每个耗时操作会以工作队列的方式在IntentService的onHandleIntent回调方法中执行,并且,每次只会执行一个线程,执行完第一个再执行第二个。
- 它本质上是一种特殊的Service,继承自Service并且本身是一个抽象类。
- 它内部是通过HandlerThread和Handler实现异步操作的。
IntentService使用方法:
关于它的使用可以参考之前写的博客:http://www.cnblogs.com/webor2006/p/4305715.html
下面总结一下:创建IntentService时,只需要实现onHandleIntent()和构造方法,onHandleIntent()为异步方法,可以执行耗时操作。
IntentService源码解析:
跟HandlerThread的源代码类似,代码也不多,如下:
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(@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; } @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 @Nullable 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)}. * This may be null if the service is being restarted after * its process has gone away; see * {@link android.app.Service#onStartCommand} * for details. */ @WorkerThread protected abstract void onHandleIntent(@Nullable Intent intent); }
而首先先看一下它的onCreate()方法:
首先会创建一个HandlerThread,然后再根据它的Looper来创建一个Handler,如下:
此时就可以在Handler中执行异步任务了。那IntentService是如何启动异步任务的呢?这里可以看一下onStrartCommand()方法:
又调用了onStart()方法:
接着就会到handler的handleMessage()方法中去处理了:
而onHandleIntent()方法是个抽象方法,由咱们自己来实现:
而其中调用停止任务时传了一个参数:
这时就会等待所有任务处理完之后才会停止,而不是立马停止。也就是如果有很多个任务都要由IntentService处理完之后,才会去让IntentService去停止,而非执行完一个就立马停止了。
它的本质就是一个封装了HandlerThread和handler的异步框架。