一、IntentService解析
(1)IntentService的特點
- IntentService自帶一個工作線程盏缤,當我們的Service需要做一些可能會阻塞主線程的工作的時候可以考慮使用IntentService砰蠢。
- IntentService通過在onCreate中創(chuàng)建HandlerThread線程、在onStartCommand發(fā)送消息到IntentService內(nèi)部類ServiceHandler中唉铜,在handleMessage中調(diào)用onHandleIntent在子線程完成工作台舱。
- 當我們通過startService多次啟動IntentService會產(chǎn)生多個Message消息。由于IntentService只持有一個工作線程潭流,所以每次onHandleIntent只能處理一個Message消息竞惋,IntentService不能并行的執(zhí)行多個intent,只能一個一個的按照先后順序完成灰嫉,當所有消息完成的時候IntentService就銷毀了拆宛,會執(zhí)行onDestroy回調(diào)方法。
(2)IntentService實現(xiàn)類
public class DownLoadIntentService extends IntentService {
public DownLoadIntentService(String name) {
super(name);
}
//運行在主線程
@Override
public void onCreate() {
super.onCreate();
}
//運行在主線程
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
//在子線程中執(zhí)行
@Override
protected void onHandleIntent(@Nullable Intent intent) {
}
}