編輯:關於 Android 程式設計
理解 IntentService,可以從三個問題入手:它是什麼?怎麼用?內部如何運作?
官方文檔的說明如下:
// 是什麼、怎麼用、如何 work 1、IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. 2、Clients send requests through startService(Intent) calls; 3、the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work. // 解釋了好處與用法 This "work queue processor" pattern is commonly used to offload tasks from an application's main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate. All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.
1、IntentService 是 Service 的子類,專門用來處理異步請求。
2、客戶端通過 startService(Intent) 把請求傳遞進來。
3、它在 onCreate() 中借助 HandlerThread 單獨開啟一個工作線程,串行處理所有請求任務,避免阻塞主線程。
4、處理完一個 Intent 對應的工作後,若沒有新請求到達,服務會自動停止;否則繼續取下一個請求。
5、內部仍採用 Handler 模式:創建一個名為 ServiceHandler 的內部 Handler,並綁定到 HandlerThread 所對應的子線程。每個 Intent 的處理邏輯都被封裝進 onHandleIntent 這個抽象方法,我們只需重寫它,按 Intent 的 action 分支處理即可。
This method is invoked on the worker thread with a request to process. Only one Intent is processed at a time, but the processing happens on a worker thread that runs independently from other application logic. So, if this code takes a long time, it will hold up other requests to the same IntentService, but it will not hold up anything else. When all requests have been handled, the IntentService stops itself, so you should not call stopSelf().
要點有兩條:其一,該方法針對不同 Intent 做不同處理,處理完後若無新請求則服務自動停止,否則 ServiceHandler 會取下一個請求再進來;其二,所有請求都在單線程中執行,不阻塞 UI 線程,但同一時間只處理一個。
特點:借助消息隊列實現,任務按 queue 順序執行;單工作線程意味著任務必須排隊;同時免去了我們自己創建線程、管理 Service 生命週期的麻煩。
相比裸用 Service 的優勢:一是使用方便、代碼簡潔,不用再手動 new Thread;二是操作完成後無需手動調用 stopSelf。
缺點也很直白:單個 worker thread 導致任務串行排隊,不適合大量並發任務的場景。
場景設計:MainActivity 啟動服務並傳入兩個參數 a、b,MyIntentService 接收後求和,通過發送廣播把結果回傳,MainActivity 收到廣播後刷新界面。
註冊/註銷廣播接收器;創建並更新 UI;傳參並啟動服務。
public class MainActivity extends AppCompatActivity {
private LinearLayout ll_container;
private BroadcastReceiver forSumReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() == Constans.ACTION_RESULT) {
int a = intent.getIntExtra(Constans.A, 0);
int result = intent.getIntExtra(Constans.RESULT, 0);
handleResult(a, result);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ll_container = (LinearLayout) findViewById(R.id.ll_container);
Log.i("TEST", "MainActivity:" + android.os.Process.myTid());
registerBroadcast();
}
private void handleResult(int a, int result) {
TextView textView = (TextView) ll_container.findViewWithTag(a);
String old = textView.getText().toString();
String newText = old.replaceAll(" 正在計算中...",
String.valueOf(result) + " 計算Success");
textView.setText(newText);
}
private void registerBroadcast() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Constans.ACTION_RESULT);
registerReceiver(forSumReceiver, intentFilter);
}
private int a = 1;
public void addTask(View view) {
int b = new Random().nextInt(101) + 1;
MyIntentService.startMyIntentService(this, a, b);
TextView textView = new TextView(this);
textView.setText(a + "+" + b + "= " + " 正在計算中...");
textView.setTag(a);
ll_container.addView(textView);
a++;
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(forSumReceiver);
}
}
public class MyIntentService extends IntentService {
public MyIntentService() {
// 必須實現父類的構造方法
super("MyIntentService");
}
@Override
public void onCreate() {
Log.i("TEST", "onCreate()");
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
Log.i("TEST", "onStart()");
super.onStart(intent, startId);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("TEST", "onStartCommand()");
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
Log.i("TEST", "onBind()");
return super.onBind(intent);
}
@Override
public void onDestroy() {
Log.i("TEST", "onDestroy()");
super.onDestroy();
}
@Override
protected void onHandleIntent(Intent intent) {
Log.i("TEST", "onHandleIntent():" + android.os.Process.myTid());
if (intent != null) {
String action = intent.getAction();
if (Constans.ACTION_FOR_SUM.equals(action)) {
int a = intent.getIntExtra(Constans.A, 0);
int b = intent.getIntExtra(Constans.B, 0);
int result = a + b;
Log.i("TEST", "result: " + result);
handleResult(a, result);
}
}
}
private void handleResult(int a, int result) {
try {
Thread.sleep(3000); // 模擬耗時計算
Intent intent = new Intent(Constans.ACTION_RESULT);
intent.putExtra(Constans.RESULT, result);
intent.putExtra(Constans.A, a);
sendBroadcast(intent);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void startMyIntentService(Context context, int a, int b) {
Intent intent = new Intent(context, MyIntentService.class);
intent.setAction(Constans.ACTION_FOR_SUM);
intent.putExtra(Constans.A, a);
intent.putExtra(Constans.B, b);
context.startService(intent);
}
}
日誌輸出如下:
07-08 10:18:51.579 I/TEST: MainActivity:30060 07-08 10:19:26.009 I/TEST: onCreate() 07-08 10:19:26.009 I/TEST: onStartCommand() 07-08 10:19:26.009 I/TEST: onStart() 07-08 10:19:26.039 I/TEST: onHandleIntent():30223 07-08 10:19:26.039 I/TEST: result: 23 07-08 10:19:29.100 I/TEST: onDestroy() 07-08 10:19:31.839 I/TEST: onCreate() 07-08 10:19:31.849 I/TEST: onStartCommand() 07-08 10:19:31.849 I/TEST: onStart() 07-08 10:19:31.869 I/TEST: onHandleIntent():30305 07-08 10:19:31.869 I/TEST: result: 52 07-08 10:19:34.899 I/TEST: onDestroy()
從線程 ID 可以看出:UI 線程是 30060,而兩次 onHandleIntent 分別跑在 30223 與 30305。這說明 onHandleIntent 確實執行在工作線程;同時,若所有請求都在同一個生命週期內完成,它們會在同一個工作線程中順序執行,否則分佈在不同線程。此外也驗證了「處理完最後一個請求後服務自動停止」這一點。

IntentService 是 Service 的子類,擁有全部生命週期方法,同時持有自己的 ServiceHandler。
public abstract class IntentService extends Service {
private volatile Looper mServiceLooper; // volatile 保證可見性
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;
}
}
可見 IntentService 實際上是 Looper、Handler 與 Service 的集合體,既有服務能力,也有消息循環能力。
onCreate:創建 HandlerThread
@Override
public void onCreate() {
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
服務創建時就啟動 HandlerThread,再取出它的 Looper 初始化 mServiceLooper,最後創建 mServiceHandler。
onStart:把請求包成 Message 入隊
@Override
public void onStart(Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
每次啟動服務,都會生成一條附帶 startId 與 Intent 的 Message 投進 MessageQueue,Looper 取到後交給 ServiceHandler 處理。
handleMessage:調用抽象方法並收尾
@Override
public void handleMessage(Message msg) {
onHandleIntent((Intent) msg.obj);
stopSelf(msg.arg1);
}
onHandleIntent 是我們需要實現的抽象方法,業務邏輯寫在這裡;處理完畢後調用 stopSelf(msg.arg1) 結束對應工作。
關於 stopSelf(msg.arg1)
這裡的 msg.arg1 是個 int 值,相當於一次請求的唯一標識。每發送一個請求都會生成唯一 id 並入隊,當它是最後一個請求(getLastStartId == startId),或者它就是最近發出的那一個時,Service 才會銷毀;若傳入 -1 則直接銷毀。這個設計保證了隊列中還有未處理任務時服務不會提前退出。
onDestroy:停止 Looper
@Override
public void onDestroy() {
mServiceLooper.quit();
}
1、IntentService 是一個基於消息的服務。每次啟動並不會立即處理事務,而是先確保 Looper、Handler 就緒,再把附帶客戶 Intent 的 Message 放入隊列;Looper 取到消息後,在 onHandleIntent 中調用我們的處理程序,全部完成後服務自行停止。也就是說 IntentService 的生命週期與任務生命週期一致,非常適合下載這類「做完即終」的場景。
2、IntentService 不適合用 bindService() 的方式啟動。通過 startService 多次啟動時,每次等價於往 MessageQueue 追加一個任務,因此天然支持多任務順序執行。
3、只有在 onHandleIntent() 中執行的代碼才跑在工作線程。另外要注意,IntentService 的停止並非因為 handleMessage 裡調用了 stopSelf(msg.arg1),而是系統在確認沒有待處理任務後自行停止的。
Unity 結合 Android 語音服務:打造 3D 語音天氣球的第三步
本系列文章共分為四個部分,循序漸進地帶你完成一個會旋轉、能播報天氣、還能用聲音操控的「3D 語音天氣球」: 一、建立可旋轉的 3D 球體;二、透過天氣服務從網路取得即時資
Android 官方 SwipeRefreshLayout 下拉刷新實戰
這是一個基於最新 v4 包實現的下拉刷新示例。整體非常簡單,畢竟用的是官方組件而非自定義,大家可以放寬心。廢話不多說,直接上代碼。 Activity 代碼 讓 Acti
用ADB自訂Android裝置名稱,路由器端一目了然
想讓Android裝置在路由器中顯示好辨識的名稱,可用ADB修改net.hostname。先Root並開啟USB除錯,執行adb devices確認連線,再用setpro
建構 Android Studio 開發環境
Android Studio 簡介 Android Studio 是 Google 推動的官方 Android 開發工具,基於 IntelliJ IDEA 打造,支援 W