IntentService是一个轻量级的执行异步任务的Service,它提供了一种任务队列消费的模式来处理任务,并支持以Intent
来传递数据,与此同时,他还会在任务结束后,停止自身,一般用来在Service
中执行耗时任务。
使用
我们先看下他怎么使用,看下类注释的说明:
* IntentService is a base class for {
@link Service}s that handle asynchronous
* requests (expressed as {
@link Intent}s) on demand. Clients send requests
* through {
@link android.content.Context#startService(Intent)} calls; the
* service is started as needed, handles each Intent in turn using a worker
* thread, and stops itself when it runs out of work.
很简单,创建IntentService
的子类,并实现onHandleIntent
方法
public class IntentServiceImpl extends IntentService {
public IntentServiceImpl(String name) {
super(name);
}
@Override protected void onHandleIntent(@Nullable Intent intent) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
然后在AndroidManifest.xml
中注册服务
<service android:name="com.github.frameworkaly.service.IntentServiceImpl" />
然后就可以按照启动普通服务的方式来启动这个服务了。
Intent intent = new Intent