一、IntentService介绍
IntentService是处理异步的一个类,继承Service。在intentservice内部有一个工作线程处理耗时操作。启动intentservice的方式跟启动一般的Service是一样的。
IntentService任务完成后自动停止,不需要我们手动控制,也不需要像Service那样调stopSelf()来停止。
Intentservice可以启动多次,但是每次只会执行一个工作线程,执行完一个后才会再执行下一个,也就是串行的。
注:Service是运行在UI线程的也就是主线程,不可执行耗时操作,否则易引起anr。IntentService内部有个执行耗时操作的工作线程(其实内部是一个handleThread),是可以执行耗时操作。
二、使用
IntentService的使用很简单,创建IntentService的时候只需要实现onHandleIntent()和构造方法即可。onHandleIntent()是异步的可执行耗时操作。
public class DownLoadIntentService extends IntentService {
public DownLoadIntentService() {
super("DownLoadIntentService");
// "DownLoadIntentService"就是工作线程的名字
}
@Override
protected void onHandleIntent(Intent intent) {
//根据Intent的不同进行不同的事务处理
}
}
AndroidManiFest.xml中需要注册Service
<service android:name=".DownLoadIntentService">
</service>
在activity中:
Intent intent = new Intent(......);
startService(intent);
三、intentservice源码分析
intentservice源码不多,才一百多行。。。。。。
1、在我们定义的intentservice的构造中
public DownLoadIntentService() {
super("DownLoadIntentService");
// "DownLoadIntentService"就是工作线程的名字
}
这里会调用IntentService中的有参的构造:
/**
* 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;
}
这里会把进程的名字保存在环境变量mName中。
2、然后在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,开启个工作线程,mServiceHandler也是工作线程的Handler。所以说IntentService可以执行耗时操作的原因就在这,内部是开启工作线程执行的。
3、
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);
}
}
在ServiceHandler的handleMessage()中调用onHandleIntent()执行自己的处理逻辑。