IntentService學習
- IntentService
- 常規用法
- 清單注冊服務
- 服務內容
- 開啟服務
IntentService
一個 HandlerThread工作線程,通過Handler實現把消息加入消息隊列中等待執行,通過傳遞的intent在onHandleIntent中處理任務。(多次調用會按順序執行事件,服務停止清除消息隊列中的消息。)
適用:線程任務按順序在后臺執行,例如下載
不適用:多個數據同時請求
1、IntentService與Service的區別
從屬性作用上來說
Service:依賴于應用程序的主線程(不是獨立的進程 or 線程)。需要主動調用stopSelft()來結束服務
不建議在Service中編寫耗時的邏輯和操作,否則會引起ANR;
IntentService:創建一個工作線程來處理多線程任務。在所有intent被處理完后,系統會自動關閉服務
2、IntentService與其他線程的區別
IntentService內部采用了HandlerThread實現,作用類似于后臺線程;
與后臺線程相比,IntentService是一種后臺服務,優勢是:優先級高(不容易被系統殺死),從而保證任務的執行。
對于后臺線程,若進程中沒有活動的四大組件,則該線程的優先級非常低,容易被系統殺死,無法保證任務的執行
常規用法
清單注冊服務
<service android:name=".SerialService"><intent-filter><action android:name="android.service.newland.serial" /></intent-filter></service>
服務內容
package com.lxh.serialport;
import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
public class SerialService extends IntentService {private static final String TAG = "SerialService lxh";private static String ACTION_Serial = "android.service.serial";public SerialService() {super("SerialService");}public static void startSS(Context context) {Intent intent = new Intent(context, SerialService.class);intent.setAction(ACTION_Serial);context.startService(intent);}@Overrideprotected void onHandleIntent(Intent intent) {if (intent != null) {final String action = intent.getAction();if (action.equals(ACTION_Serial)) {
// mSerialInter = new modeSerialInter();
// SerialManage.getInstance().init(mSerialInter);
// SerialManage.getInstance().open();}}}
}
開啟服務
SerialService.startSS(this);
感謝互聯網
適合閱讀文章分享
Android IntentService詳解
與君共勉!待續
歡迎指錯,一起學習