IntentService继承自Service,可以处理异步请求。IntentService和Service的区别在于,用户可把任务通过startService()方法把任务封装在Intent中交于IntentService处理。IntentService可以处理多个任务,只需要实现在onHandleIntent()方法中实现每个任务的处理逻辑即可(用户通过调用startService来提交任务)。
Service默认运行在主线程中的,而IntentService则会自动开启子线程来处理请求。同时,IntentService对请求的处理是串行的,即按照提交的先后顺序处理请求,即使某个请求是耗时任务,也只有在该任务结束之后才会处理下一个任务。Intent对任务的处理是通过Handler完成的。在所有任务处理完毕之后会自动停止,而Service需要程序员主动调用stopService()方法才会停止。
IntentService的简单实现
public class MyIntentService extends IntentService {
//必须重写这个方法,否则Service启动时会出错
public MyIntentService(){
super("MyIntentService");
}
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public MyIntentService(String name) {
super(name);
}
/*
*请求的处理
*/
@Override
protected void onHandleIntent(@Nullable Intent intent) {
Log.d(TAG, "onHandleIntent: current thread = " + Thread.currentThread().getId());
String action = intent.getAction();
Log.d(TAG, "action = " + action);
switch (action){
case "com.guohao.task1":
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d(TAG, "onHandleIntent: task1 finished !");
break;
case "com.guohao.task2":
Log.d(TAG, "onHandleIntent: task2 finished !");
break;
}
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate: ");
}
@Override
public void onStart(@Nullable Intent intent, int startId) {
super.onStart(intent, startId);
Log.d(TAG, "onStart: ");
}
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand: ");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
IntentService的启动(任务请求的发送)
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: current thread = " + Thread.currentThread().getId());
Intent intent;
switch (v.getId()){
case R.id.btn_start_work_1:
Log.d(TAG, "onClick: ");
intent = new Intent(this, MyIntentService.class);
intent.setAction("com.guohao.task1");
startService(intent);
break;
case R.id.btn_start_work_2:
intent = new Intent(IntentServiceTestActivity.this, MyIntentService.class);
intent.setAction("com.guohao.task2");
startService(intent);
break;
}