編輯:關於 Android 程式設計
Service 是 Android 四大元件之一。它沒有 UI 介面,可以在後台執行長時間的操作。其他元件可以 start 一個 Service,啟動之後它會在後台持續運行,無管用戶是否切換到了別的應用程式。此外,其他元件還可以 bind 到 Service 上與之互動,甚至進行跨行程操作(IPC)。典型用途包括:在後台處理網路請求、播放音樂、執行檔案 IO,或與 Content Provider 互動。
Started(已啟動)
當其他元件呼叫 startService() 啟動的 Service 就是 started。一旦啟動,它會在後台無限運行下去,即使啟動它的元件已經被銷毀。這種 Service 通常只做單一操作,而且不回傳結果給呼叫者,例如透過網路下載或上傳檔案。工作結束時,Service 必須手動把自己停掉。
Bound(已綁定)
當其他元件呼叫 bindService() 綁定時,Service 就是 bound。它提供客戶端/服務端介面,允許元件與 Service 互動、送出請求、取得結果,甚至跨行程操作。Bound Service 只在其他元件綁定於它時存活;多個元件可以同時綁定同一個 Service,但當所有元件都解綁後,Service 就被銷毀。
雖然這裡分開討論,但一個 Service 可以同時支援兩種型態——取決於你是否實作了 onStartCommand()(允許被 start)與 onBind()(允許被綁定)。
重要提醒:Service 運行在宿主行程的主執行緒上,它不會自己建立執行緒,也不會跑在獨立行程中(除非你明確指定)。因此若 Service 要做耗 CPU 或阻塞的操作(播放 MP3、網路請求等),你必須在內部自行建立新執行緒,否則 ANR 風險很高,主執行緒也無法專注在 UI 操作上。
建立 Service 時必須繼承 Service 或其子類,並覆寫以下關鍵回呼:
startService() 時觸發。此方法執行後 Service 即在後台無限運行,你有責任在工作結束後呼叫 stopSelf() 或 stopService() 將它銷毀。若只提供綁定功能,則不需實作。bindService() 時觸發。必須回傳一個 IBinder 作為與 Service 互動的介面;若不允許綁定,回傳 null。Android 只在記憶體不足時才會強制終止 Service,因為系統必須優先保住持有用戶焦點的 Activity 所需的資源。優先順序大致如下:
如果 Service 是被 started 的,你必須讓它能優雅地面對系統重啟:一旦資源恢復,系統會依 onStartCommand() 的回傳值決定是否重啟它。
與 Activity 一樣,所有 Service 都必須在 manifest 中宣告:
<manifest ...>
...
<service android:name=".ExampleService">
...
</service>
</manifest>
android:name 是唯一必填屬性,指定 Service 的類別名稱。應用發布後不應再修改這個名字,否則用明確 Intent 來 start 或 bind 的程式碼會有 crash 風險。
為了安全性,start 或 bind Service 時一律使用明確 Intent,且不要為 Service 宣告 intent-filter。若確實需要間接啟動,可以設定 filter 並排除特定元件名稱,但務必用 setPackage() 為 Intent 指定套件,確定性才足夠。
另一個作法是加入 android:exported="false",確保 Service 只對自己的應用可用——即使其他應用使用明確 Intent 也無法啟動它。
大多數 started Service 不需要處理並發請求,因此繼承 IntentService 通常是最省事的做法。它會幫你處理:
onStartCommand() 的 Intent,且與主執行緒獨立。onHandleIntent(),不必擔心多執行緒問題。stopSelf()。onBind() 的預設實作,回傳 null。onStartCommand() 的預設實作,把 Intent 送進工作佇列後交給 onHandleIntent()。
public class HelloIntentService extends IntentService {
/** 建構子必須呼叫 super IntentService(String),參數為工作執行緒的名稱 */
public HelloIntentService() {
super("HelloIntentService");
}
/**
* IntentService 會在預設工作執行緒上呼叫此方法,
* 方法回傳後,IntentService 會視情況停止服務。
*/
@Override
protected void onHandleIntent(Intent intent) {
// 這裡通常會做下載檔案之類的工作,範例中單純睡 5 秒
long endTime = System.currentTimeMillis() + 5 * 1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
wait(endTime - System.currentTimeMillis());
} catch (Exception e) { }
}
}
}
}
就這樣:一個建構子加上 onHandleIntent()。若你要覆寫 onCreate()、onStartCommand() 或 onDestroy(),務必記得呼叫父類實作,否則 IntentService 無法正確管理它的工作執行緒。
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags, startId);
}
若 Service 需要處理多執行緒(不是透過工作佇列),就該直接繼承 Service。以下範例實作了與上面 IntentService 版本相同的功能:
public class HelloService extends Service {
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
// 接收執行緒訊息的 Handler
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
// 這裡通常會做下載檔案之類的工作,範例中單純睡 5 秒
long endTime = System.currentTimeMillis() + 5 * 1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
wait(endTime - System.currentTimeMillis());
} catch (Exception e) { }
}
}
// 用 startId 停止,避免在處理另一個任務途中把服務停掉
stopSelf(msg.arg1);
}
}
@Override
public void onCreate() {
// 建立獨立執行緒,避免阻塞主執行緒;
// 同時設為背景優先級,讓 CPU 密集工作不干擾 UI
HandlerThread thread = new HandlerThread("ServiceStartArguments",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
// 每個啟動請求都送一則訊息,並帶入 startId
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
// 被系統回收後重新建立
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null; // 不提供綁定
}
@Override
public void onDestroy() {
Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
}
}
可以看到工作量比 IntentService 多不少。但因為請求是在 onStartCommand() 中處理的,你可以並發處理多個請求(為每個請求建立執行緒立即執行,而非排隊等待)。
onStartCommand(),但不會重送最後一個 Intent(改傳 null),除非有 pending intent。適合媒體播放器這類「不執行具體命令、只是持續運行等待新任務」的 Service。onStartCommand(),並重送最後一個 Intent;pending intents 也會依序送達。適合下載檔案這種需要立刻被喚醒的情境。在 Activity 或其他元件中,傳入指定 Service 的 Intent 即可啟動:
Intent intent = new Intent(this, HelloService.class); startService(intent);
startService() 會立即回傳,系統隨後呼叫 onStartCommand();若 Service 尚未運行,會先呼叫 onCreate()。請注意不要直接呼叫 onStartCommand()。
若 Service 不提供綁定,Intent 就是唯一的對外溝通管道。反之,若 Service 需要回傳結果,啟動它的客戶端可以建立一個用於廣播的 PendingIntent(getBroadcast())傳進去,Service 就能透過廣播送出結果。
多次啟動請求會導致多次 onStartCommand() 呼叫,但只需要一次停止請求就能停掉 Service。
停止 Service:started Service 必須自行管理生命週期。系統不會主動停它(除非要回收資源),因此 Service 要呼叫 stopSelf(),或由其他元件呼叫 stopService()。
若 Service 在 onStartCommand() 中並發處理請求,處理完一個就停掉自己顯然是錯的——你可能已經收到了新請求。這時應使用 stopSelf(int),傳入對應的 startId。若在你呼叫 stopSelf(int) 前又來了一個啟動請求,ID 對不上,Service 就不會被停掉。
工作完成後主動停掉 Service,對節省系統資源與電量都很重要。另外,即使 Service 有啟用 binding,只要收到過 onStartCommand() 呼叫,仍需手動停止。
Bound Service 讓應用元件呼叫 bindService() 建立長時間存在的連接(通常不搭配 startService())。當你想讓 Activity 與 Service 互動,或透過 IPC 把功能開放給其他應用時,就該用它。
實作上要定義 onBind() 並回傳 IBinder,它定義了通訊介面。客戶端呼叫 bindService() 取得介面後即可呼叫 Service 的方法。Service 只在其綁定的元件存在時存活,因此當沒有客戶端綁定時系統會自動銷毀它——不需要像 started Service 那樣手動停止。
多個客戶端可同時綁定同一個 Service;每個客戶端用完後呼叫 unbindService() 解綁,全部解綁後 Service 即被銷毀。由於實作方式較多、複雜度也高於 started Service,細節建議參考官方 Bound Services 專章。
Service 運行期間可以透過 Toast 或狀態欄通知提醒用戶事件。一般來說,當後台任務完成時(例如檔案下載完畢),用狀態欄通知是最合適的做法:用戶在展開的視圖中點選通知後,可以直接開啟一個 Activity 做後續操作。
前台 Service 被視為用戶可感知的,因此不是低記憶體時的回收候選。它必須在狀態欄有一則屬於「進行中」的通知,且除非 Service 被停止或移出前台,通知不會消失。
典型例子是音樂播放器:用戶明確知道它在運作,狀態欄通知可以顯示目前播放的歌曲,並讓用戶點擊跳回播放器 Activity。
Notification notification = new Notification(
R.drawable.icon, getText(R.string.ticker_text), System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this,
getText(R.string.notification_title),
getText(R.string.notification_message),
pendingIntent);
startForeground(ONGOING_NOTIFICATION_ID, notification);
注意:通知的 ID 不能為 0。
要移出前台,呼叫 stopForeground(),它接受一個 boolean 參數決定是否同時移除狀態欄通知。這個方法不會停止 Service;若你想在前台狀態下停止 Service,通知也會一併消失。
public class ExampleService extends Service {
int mStartMode; // 被回收後的行為
IBinder mBinder; // 供客戶端綁定的介面
boolean mAllowRebind; // 是否使用 onRebind
@Override
public void onCreate() {
// Service 正在被建立
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Service 因 startService() 而啟動
return mStartMode;
}
@Override
public IBinder onBind(Intent intent) {
// 有客戶端以 bindService() 綁定
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
// 所有客戶端都已 unbindService()
return mAllowRebind;
}
@Override
public void onRebind(Intent intent) {
// onUnbind() 已呼叫過之後,又有客戶端綁定
}
@Override
public void onDestroy() {
// Service 不再被使用,即將銷毀
}
}
與 Activity 不同,這些回呼並不要求呼叫父類實作。
實作這些方法後,你可以監控兩個循環:
(1)完整生命週期:從 onCreate() 到 onDestroy() 回傳。類似 Activity,Service 在 onCreate() 做初始化、在 onDestroy() 釋放資源。例如音樂播放器可以在 onCreate() 建立播放執行緒,在 onDestroy() 停掉它。不管 Service 是用 startService() 還是 bindService() 建立,這兩個回呼都會被呼叫。
(2)活動時間:從 onStartCommand() 或 onBind() 開始。這兩個方法分別接收 startService() 或 bindService() 傳入的 Intent。若 Service 是 started,活動時間會延續到生命週期結束;若是 bound,則在 onUnbind() 回傳時結束。
最後一個容易誤會的點:被 stopSelf() 或 stopService() 停掉的 started Service,並沒有對應的回呼(不存在 onStop())。因此除非 Service 仍綁定著某個客戶端,一旦停止系統就會直接銷毀它,onDestroy() 是唯一會收到的通知。
從安全角度理解 Android BroadcastReceiver(上)
BroadcastReceiver 的基本用法 BroadcastReceiver 是 Android 四大元件之一,常用於接收系統或應用程式內部的廣播訊息。基本流程通常
Android PopupWindow 使用詳解與 6.0 源碼差異
本文參考〈Android PopupWindow 用法解析〉一文進行學習,透過實例與源碼分析掌握了 PopupWindow 的使用方式。原文最後「補充案例:彈窗不消失,但
Android 自定義 SwipeLayout 實現列表項左滑顯示刪除按鈕
滑動刪除可以拆成兩個區域來看:內容區用於承載正常顯示的 View,操作區用於放置刪除按鈕。預設狀態下操作區隱藏,內容區填滿整個容器,操作區永遠位於內容區右側。開始滑動時,
Android 增量更新實戰:用 bsdiff 生成補丁、bspatch 端上合成
增量更新到底是什麼 增量更新其實並不是新鮮事物,早在 Android 早期就已經有團隊在用了,只是真正把它做成產品能力的,大多是有實力的大廠。做法並不神秘:服務端保存舊版