概述
IntentService是Service的子類,通過實(shí)現(xiàn)onHandleIntent(Intent intent)抽象方法來執(zhí)行耗時操作摄凡,耗時操作執(zhí)行完成會自動停止當(dāng)前Service续徽;
構(gòu)造方法
- IntentService(String name)
name為線程名稱,需要注意的是亲澡,繼承IntentService類時子類的構(gòu)造方法必須是空參數(shù)的钦扭,否則無法實(shí)例Service會報異常java.lang.InstantiationException;
內(nèi)部類
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)方法客情,消息處理完成會調(diào)用stopSelf(int startId)結(jié)束當(dāng)前Service其弊;
成員變量
- Looper mServiceLooper
IntentService對應(yīng)工作線程的Looper對象; - ServiceHandler mServiceHandler
IntentService對應(yīng)工作線程的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);
}
在服務(wù)onCreate時開啟一個HandlerThread子線程,獲取子線程Looper對象并創(chuàng)建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);
}
在服務(wù)onStart時給ServiceHandler發(fā)送消息籽御,ServiceHandler會調(diào)用onHandleIntent(Intent intent)方法處理消息(一般是耗時操作)
- onDestroy()
@Override
public void onDestroy() {
mServiceLooper.quit();
}
在服務(wù)onDestroy時退出消息循環(huán);
- onHandleIntent(Intent intent)
在子類中實(shí)現(xiàn)該方法惰匙,用于執(zhí)行耗時操作技掏,其中intent參數(shù)由startService(intent)時傳入在onStart(Intent intent, int startId)中接收。
實(shí)例
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");
}
}