Service 是 Android 四大組件之一,默默的工作在后臺(tái)(當(dāng)然也有前臺(tái)服務(wù))飒房,它的使用我這里就先不做詳細(xì)介紹,今天主要介紹的是 Service 的一個(gè)子類 IntentService,為什么要有 IntentService 這個(gè)類呢凝果?下面就來(lái)稍微說(shuō)說(shuō)我的理解郁岩。
其實(shí) IntentService 簡(jiǎn)化了啟動(dòng)服務(wù)的實(shí)現(xiàn)婿奔,我們按照正常的 startService() 就可以啟動(dòng) IntentService 了。
Service 本身是在 UI 線程運(yùn)行的驯用,IntentService 則是把任務(wù)放在工作線程去完成脸秽,而且在使用 Service 時(shí)我們要自己控制 Service 的生命周期,而 IntentService 會(huì)在結(jié)束完任務(wù)后自己調(diào)用 stopSelf() 方法來(lái)停止自己蝴乔。
下面我們來(lái)看看如何使用 IntentService记餐。
我們自定義一個(gè) IntentService 其實(shí)很簡(jiǎn)單,只需要我們自己實(shí)現(xiàn) onHandleIntent() 以及調(diào)用一下 IntentService 的構(gòu)造就可以了薇正,就像這個(gè)官方給示例就可以了片酝。
public class HelloIntentService extends IntentService {
/**
* A constructor is required, and must call the super [IntentService(String)](https://developer.android.com/reference/android/app/IntentService.html#IntentService(java.lang.String))
* constructor with a name for the worker thread.
*/
public HelloIntentService() {
super("HelloIntentService");
}
/**
* The IntentService calls this method from the default worker thread with
* the intent that started the service. When this method returns, IntentService * stops the service, as appropriate.
*/
@Override
protected void onHandleIntent(Intent intent) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// Restore interrupt status.
Thread.currentThread().interrupt();
}
}
}
簡(jiǎn)單的介紹完使用后囚衔,再來(lái)說(shuō)說(shuō)原理,為什么 onHandleIntent() 是運(yùn)行在后臺(tái)的雕沿,又為什么執(zhí)行完了任務(wù)自己會(huì)結(jié)束掉自己练湿。
在當(dāng)我們啟動(dòng) IntentService 時(shí)候,它也和普通服務(wù)一樣审轮,先調(diào)用 onCreate()肥哎,然后調(diào)用 onStartCommand(),由 onStartCommand() 調(diào)用 onStart() 從而開(kāi)始了 Service 的運(yùn)行疾渣。
onCreate() 和 onStart() 是兩個(gè)比較重要的方法篡诽,我們來(lái)分別看一下他們的內(nèi)部的實(shí)現(xiàn):
@Override
public void onCreate() {
// 先調(diào)用父類的 onCreate(),但其實(shí)只是一個(gè)空函數(shù)而已
super.onCreate();
// 創(chuàng)建一個(gè)自帶 Looper 的工作線程榴捡,并通過(guò) start() 讓線程開(kāi)始工作
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
// 拿到工作線程的 Looper
mServiceLooper = thread.getLooper();
// mServiceHandler 是 IntentService 內(nèi)部定義的一個(gè) Handler
// 在工作線程使用 Handler 需要手動(dòng)傳遞一個(gè) Looper 進(jìn)去杈女,不然會(huì)報(bào)錯(cuò)的
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public void onStart(@Nullable Intent intent, int startId) {
// 在 onStartCommand 中調(diào)用 onStart(intent, startId)
// 在 onStart() 直接發(fā)了一下消息
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
// 下面我們來(lái)看看 mServiceHandler
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
// 消息發(fā)送過(guò)來(lái)就直接執(zhí)行 onHandleIntent()
onHandleIntent((Intent)msg.obj);
// 執(zhí)行完 onHandleIntent() 后結(jié)束自身
stopSelf(msg.arg1);
}
}
通過(guò)上面的部分代碼我們不難看出,IntentService 通過(guò)新建了一個(gè)工作線程吊圾,并在工作線程中使用 Handler 來(lái)處理消息达椰,處理消息的過(guò)程也就是執(zhí)行任務(wù)和結(jié)束自身的過(guò)程,所以 IntentService 使得我們更方便的使用一個(gè)無(wú)需管理自身生命周期项乒,且任務(wù)運(yùn)行在工作線程的服務(wù)啰劲。
上面我們介紹了 IntentService 中一些關(guān)鍵的方法,下面貼出了 IntentService 的源碼:
public abstract class IntentService extends Service {
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private String mName;
private boolean mRedelivery;
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);
}
}
public IntentService(String name) {
super();
mName = name;
}
public void setIntentRedelivery(boolean enabled) {
mRedelivery = enabled;
}
@Override
public void onCreate() {
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public void onStart(@Nullable Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
@Override
public void onDestroy() {
// 退出Looper
mServiceLooper.quit();
}
@Override
@Nullable
public IBinder onBind(Intent intent) {
return null;
}
@WorkerThread
protected abstract void onHandleIntent(@Nullable Intent intent);
}
閱讀源碼從我開(kāi)始板丽,我也會(huì)從相對(duì)簡(jiǎn)單的部分開(kāi)始呈枉,希望對(duì)大家有用。