**
1.用法解析
**
IntentService是Service的子类,会默认开启一个工作线程,逐一处理所有请求,直到所有请求都处理完成后,自动停止服务,无需再手动进行停止。
只需要实现onHandleIntent即可。
public class TestIntentService extends IntentService {
private static final String TAG = “TestIntentService”;
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public TestIntentService(String name) {
super(name);
}
public TestIntentService() {
super("TestIntentService");
}
@Override
public void onCreate() {
super.onCreate();
Log.e(TAG, "onCreate--" + Thread.currentThread().getName());
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e(TAG, "onDestroy");
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
Log.e(TAG, "onHandleIntent--" + Thread.currentThread().getName());
}
}
在活动中启动IntetnService。
private void startIntentService() {
Intent intent = new Intent(this, TestIntentService.class);
startService(intent);
}
startIntentService();
startIntentService();
startIntentService();
打印日志如下:
通过日志,可发现,在IntentService中,onHandleIntent处于独立的工作线程中,所有任务完成后,会自动停止,无需再手动关闭服务。
2.核心源码
IntentService会在onCreate中创建新线程,获得looper后,传入handle中,通过消息传输,在handleMessage完成任务,完成后调用stopSelf()。
同时首次创建服务时,才会调用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);
}
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);
}
}