Service本身并不会创建一个新的线程或者存在于一个新的线程中,那么进行一些耗时操作时就需要自己创建新的线程,这毫无疑问是比较麻烦的,这时Service的一个子类IntentService可以解决这个问题。
开发方法:
继承IntentService,覆写onHandleIntent函数,在该函数中完成自己的耗时操作即可。
注意:
任务执行完毕之后,IntentService会调用stopSelf函数自我销毁
onBind和 onStartCommand默认实现,无需重写
示例:
public class MyIntentService extends IntentService {
public MyIntentService() {
super("MyIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
// 耗时操作
}
}
相关链接
Android-服务Service(1)-介绍及startService调用
Android-服务Service(2)-bind绑定Service及两种生命周期
Android-服务Service(3)-IntentService