概述
IntentService是Service的子类,通过实现onHandleIntent(Intent intent)抽象方法来执行耗时操作,耗时操作执行完成会自动停止当前Service;
构造方法
- IntentService(String name)
name为线程名称,需要注意的是,继承IntentService类时子类的构造方法必须是空参数的,否则无法实例Service会报异常java.lang.InstantiationException;
内部类
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);
}
}
Handler的子类,消息处理会交给IntentService的onHandleIntent(Intent intent)方法,消息处理完成会调用stopSelf(int startId)结束当前Service;
成员变量
- Looper mServiceLooper
IntentService对应工作线程的Looper对象; - ServiceHandler mServiceHandler
IntentService对应工作线程的ServiceHandler对象; - String mName
线程名称;
成员方法
- onCreate()
@Override
public void onCreate() {
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
在服务onCreate时开启一个HandlerThread子线程,获取子线程Looper对象并创建ServiceHandler对象;
- onStart(Intent intent, int startId)
@Override
public void onStart(Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
在服务onStart时给ServiceHandler发送消息,ServiceHandler会调用onHandleIntent(Intent intent)方法处理消息(一般是耗时操作)
- onDestroy()
@Override
public void onDestroy() {
mServiceLooper.quit();
}
在服务onDestroy时退出消息循环;
- onHandleIntent(Intent intent)
在子类中实现该方法,用于执行耗时操作,其中intent参数由startService(intent)时传入在onStart(Intent intent, int startId)中接收。
实例
public class TestService extends IntentService {
public static final String TAG = "Lee";
public TestService() {
super("test");
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d(TAG, "onHandleIntent, intent = " + intent);
// 模拟耗时操作
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy");
}
}