[TOC]
1.IntentService的简单使用
使用IntentService只需自定义类继承该类,并在构造函数中调用super()方法和实现 onHandleIntent()方法即可。
如下代码所示:
class MyIntentService:IntentService("MyIntentService") {
override fun onHandleIntent(intent: Intent?) {
//在这里实现一些业务
LogUtil.i("hugo","onHandleIntent")
Thread.sleep(5000)
}
}
// AndroidManifest 中配置
<application>
<service android:name=".MyIntentService"/>
</application>
//MainActivity
btn_intent_service.setOnClickListener {
startService(Intent(this,MyIntentService::class.java))
}
这样就可以了。是不是很简单,让我们来看一看IntentService是怎么实现的吧。
2.IntentService的具体实现
1.在IntentService 的构造方法中需要传入一个name
/**
* 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;
}
而这个name 是用于 创建线程时给线程命名的。
2.在IntentService 首次创建时时系统会调用 onCreate() 方法 IntentService在这个方法中会创建一个创建一个了一个线程,并启动了该线程 如下:
@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();
//获取线程的looper
mServiceLooper = thread.getLooper();
//创建一个Handler
mServiceHandler = new ServiceHandler(mServiceLooper);
}
3.在别的组件启动IntentService时,IntentService会调用onStartCommand() 方法
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
可以看到IntentService 在 onStartCommand() 方法中调用了 onStart()方法
@Override
public void onStart(@Nullable Intent intent, int startId) {
//获取一个Message
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
//把Message发送给 Handler
mServiceHandler.sendMessage(msg);
}
这个onStart() 方法主要就是获取一个Message 并把Intent存入其中 把Message发送给Handler
3.那我们来看一下Handler是怎么实现的
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.java
protected abstract void onHandleIntent(@Nullable Intent intent);
可以看到Handler里面的实现也很简单,就是把Message中传过来的Intent传入 IntentService的抽象方法onHandleIntent() 中,这个方法就是我们实现进行业务操作的方法,然后就是stopSelf() 方法关闭这个Service。
3.总结
看了IntentService的源码后发现IntentService主要就是在创建时创建了一个线程来进行来进行业务作业。 在调用 onStartCommand() 方法时把Intent发送给Handler,在作业完成后会调用 stopSelf() 方法关闭Service。