IntentService是Service的子类,和 Service 不同的是 IntentService 自带一个子线程,该子线程支持消息消息循环,Service 中的所有耗时任务都可以放到该子线程中来完成。该子线程使用的 HandlerThread 类型,是一个带 Looper 的可以关联 handler 的线程。IntentService 自带的 handler 是 ServiceHandler。在 Service 的 onCreate 中创建的该 thread,在 Service 的 onDestroy 中通过 looper 的 quit 方法结束线程。
1.IntentService特征
有独立的 worker 线程来处理 Intent 请求,默认 handler 会调用onHandleIntent() 方法来处理;
所有请求处理完成后,IntentService会自动停止,无需调用stopSelf()方法停止Service;
为Service的onBind()提供默认实现,返回null;
为Service的onStartCommand提供默认实现,将请求Intent封装成了消息,让 ServiceHandler 调用 onHandlerIntent 方法在子线程中来处理;
2.使用步骤
1.继承IntentService类,并重写onHandleIntent()方法
MyIntentService.java
public class MyIntentService extends IntentService {
public MyIntentService() {
super("MyIntentService");
}
@Override
public void onCreate() {
super.onCreate();
System.out.println("----onCreate---");
}
@Override
protected void onHandleIntent(Intent intent) {
// IntentService会使用单独的线程来执行该方法的代码
// 该方法内执行耗时任务,比如下载文件,此处只是让线程等待20秒
long endTime = System.currentTimeMillis() + 20 * 1000;
System.out.println("onStart");
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
wait(endTime - System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println("----耗时任务执行完成---");
}
@Override
public void onDestroy() {
super.onDestroy();
System.out.println("----onDestroy---");
}
}
2.通过 startService 调用 Service 功能
MainActivity.java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.intentService:
Intent intent = new Intent(this, MyIntentService.class);
startService(intent);
break;
case R.id.service:
break;
default:
break;
}
}
}