简介
IntentService是Service类的子类,用来处理异步请求。客户端可以通过startService(Intent)方法传递请求给IntentService,IntentService通过handlerThread处理每个Intent对象,执行完所有的工作之后自动停止Service。
基本使用
由于IntentService是一个抽象类,故我们需要继承并实现相应的方法才能使用。
MyIntentService.java
public class MyIntentService extends IntentService {
public MyIntentService(String name) {
super(name);
// TODO Auto-generated constructor stub
}
@Override
protected void onHandleIntent(Intent intent) {
// TODO 做耗时操作
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
Activity.java
Intent intent = new Intent(this,MyIntentService.class);
startService(intent);
startService(intent);
使用起来是非常简单的,我们需要注意的是,onHandleIntent方法会处理intent,当不再有intent需要处理的时候,则会执行onDestroy方法销毁。
源码分析
我们先看下ItentService的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);
}
我们发现,在onCreate里主要是做了初始化工作:创建HandlerThread,并得到mServiceLooper,然后使用looper来构造一个ServiceHandler对象。ServiceHandler是IntentService的内部类:
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);
}
}
onHandleIntent方法是IntentService里的一个抽象方法,需要子类去实现,它的主要作用是去解析intent里的参数,然后去执行后台任务,如果后台只有一个任务,那么执行完onHandleIntent方法后就会调用stopSelf方法销毁此服务。具体代码如下:
public final void stopSelf(int startId) {
if (mActivityManager == null) {
return;
}
try {
mActivityManager.stopServiceToken(
new ComponentName(this, mClassName), mToken, startId);
} catch (RemoteException ex) {
}
}
然后,我们看看onStartCommond方法:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
里面调了onStart方法,继续:
@Override
public void onStart(Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
这段代码,我们再熟悉熟悉不过了。发送消息。
总结
a.IntentService内部是通过消息机制将intent分配给onHandleIntent
去处理,故在onHandleIntent里是可以执行耗时任务的。
b.onHandleIntent处理掉所有的Intent后才会调用stopSelf方法去销毁IntentService。
c.后台任务是串行顺序排列,顺序依照startService的顺序。