1、源码解析
IntentService注释:
IntentService is a base class for {@link Service}s that handle asynchronous requests (expressed as {@link Intent}s) on demand. Clients send requests through {@link android.content.Context#startService(Intent)} calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.
大概意思是:IntentService是基于Service的一个扩展类,主要用于处理异步请求;可以通过startService提交请求,该service在需要的时候被创建,请求是在工作线程中处理的,当完成所有任务后,该service会自动关闭。
源码:
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);
}
}
public IntentService(String name) {
super();
mName = name;
}
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);
}
@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();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@WorkerThread
protected abstract void onHandleIntent(Intent intent);
}
通过上面的源码阅读,可以看出,它在onCreate()中初始化了一个HandlerThread,并关联了ServiceHandler;
然后在每次调用onStartCommand(),回调了onStart()方法,通过ServiceHandler发送一个msg,消息体中包含我们的intent;最后handleMessage中回调onHandleIntent()方法,用于处理intnet事件;回调完成后调用stopSelf。
注意这个stopSelf(msg.arg1),msg.arg1为int值,相当于一个请求的唯一标识,每发送一个请求,会生成一个唯一标识,然后将请求放入队列;当请求全部执行完成后(最后一个请求也就相当于getLasrStartId == startId)或者当前发送的标识是最近发出的那一个(getLasrStartId == startId),会销毁service。如果传入-1则直接销毁。
当service销毁会调用onDestory(),在onDestroy()中会释放Looper:mServiceLooper.quit()。
参考:
http://blog.csdn.net/lmj623565791/article/details/47143563