編輯:關於 Android 程式設計
Service 是 Android 四大元件之一。當你有些「耗時但不需要跟使用者互動」的工作要做時,就該考慮它。常見場景包括:後台上傳與下載、防毒或監控類應用需要常駐並由 Intent 驅動、聊天與社群應用需要定時送心跳維持線上狀態等。
有兩個常見誤解要先打掉:
它有兩種啟動方式,也是它的兩個主要特性:
Context.startService():告訴系統有後台任務需要執行,請系統安排。Context.bindService():對外暴露功能,建立一條較長的連線,讓 Service 能與多個 client 溝通互動。兩種啟動方式下的生命週期對比如下:
startService() 啟動:訪問者與 Service 之間沒有關聯,即使發起者離開了,Service 依然運行,必須由 Context.stopService() 結束,結束時會回呼 onDestroy()。適合彼此沒有互動需求的情況。
Service 建立時呼叫
onCreate();建立之後重複呼叫startService()不會再次觸發onCreate(),Service 不會被重複建立,但每次你都會走一次onStartCommand()(接著是已棄用的onStart())。
bindService() 啟動:訪問者與 Service 綁在一起,訪問者一旦退出,Service 隨之終止。適合需要呼叫 Service 方法或傳遞參數的情況。
Service 尚未建立時,系統先呼叫
onCreate(),接著是onBind(),此時兩者完成綁定。若訪問者要與 Service 通訊,onBind()必須回傳一個Ibinder物件。訪問者離開時,系統先呼叫onUnbind(),再呼叫onDestroy()。若 Service 已被綁定,重複呼叫bindService()不會造成重複建立與綁定。
解除綁定用 unbindService(),它同樣會觸發 onUnbind() → onDestroy()。要注意的是重複呼叫 unbindService() 會丟出 java.lang.IllegalArgumentException: Service not registered。
因此,若只在 Activity 可見期間需要與 Service 互動,應該在 onStart() 綁定、onStop() 解除綁定;若希望 Activity 即使停止也能收到回應,可以在 onCreate() 綁定、onDestroy() 解除綁定。但這代表 Activity 整個生命週期都佔著這條連線,如果 Service 在另一個進程,反而增加了該進程的負擔,讓它更容易被系統回收。
對同一個 Service 同時使用 startService() 與 bindService(),onCreate() 依然只會執行一次。這種情況下,必須等到 unBindService() 之後,Service 才能被真正銷毀。
client: startService() -> bindService() -> stopService() / unBindService() -> unBindService() / stopService() service: onCreate() -> onStartCommand() -> onStart() -> onBind() -> onServiceConnected() -> onUnBind() -> onDestroy() client: bindService() -> startService() -> stopService() / unBindService() -> unBindService() / stopService() service: onCreate() -> onBind() -> onServiceConnected() -> onStartCommand() -> onUnBind() -> onDestroy()
幾個容易踩到的細節:
另外,onStartCommand(Intent intent, int flags, int startId) 的參數與回傳值值得留意:flags 預設為 0(對應 START_STICKY_COMPATIBILITY);startId 是唯一整數,多次呼叫時呈 0、1、2… 遞增。回傳值則有三種選擇:
START_NOT_STICKY:Service 因記憶體不足被 kill 後,即使日後記憶體充足也不會重建,除非 client 明確再次 startService。START_STICKY:被 kill 後,系統在記憶體足夠時會嘗試重建並回呼 onStartCommand(),但此時 Intent 為 null(PendingIntent 除外)。START_REDELIVER_INTENT:與上者差異在於回呼時 Intent 非空,會是最後一次 startService 傳入的 Intent。建立 Service 類別,並設計一個內部 Binder 子類別,把要對外開放的 public 方法定義在裡面。
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class DemoService extends Service {
private static final String TAG = "DemoService";
private static final int NOTIFICATION = 101;
private NotificationManager mNM;
private final DemoBinder demoBinder = new DemoBinder();
public class DemoBinder extends Binder {
public DemoService getService() {
return DemoService.this;
}
public void upload() {
Log.d(TAG, "upload: ");
}
}
// 允許綁定時回傳 IBinder,不允許則回傳 null
@Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "onBind: ");
return demoBinder;
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate: ");
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
showNotification();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand: ");
return super.onStartCommand(intent, flags, startId);
}
@Override
public boolean onUnbind(Intent intent) {
Log.d(TAG, "onUnbind: ");
return super.onUnbind(intent);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
mNM.cancel(NOTIFICATION);
}
private void showNotification() {
PendingIntent contentIntent = PendingIntent.getActivity(
this, 0, new Intent(this, MainActivity.class), 0);
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setTicker("Service 已啟動")
.setWhen(System.currentTimeMillis())
.setContentTitle("DemoService 正在運行")
.setContentText("測試 Service")
.setContentIntent(contentIntent)
.getNotification();
mNM.notify(NOTIFICATION, notification);
}
}
別忘了在 AndroidManifest.xml 註冊:
<service
android:name=".DemoService"
android:enabled="true"
android:exported="true" />
Service 元素的常見屬性:
android:name:服務類別名稱。android:label:服務顯示名稱,不設定則預設用類別名稱。android:icon:服務圖示。android:permission:宣告此服務的權限,只有具備該權限的應用才能控制或連線。android:process:是否運行在另一個進程,設定後會在包名後附加該字串作為進程名。android:enabled:設為 true 時服務會被系統啟動,不設定預設為 false。android:exported:是否允許其他應用控制或連線,不設定預設為 false。client 端透過 bindService(Intent service, ServiceConnection conn, int flags) 的 conn 參數建立與 Service 的聯繫:
public class MainActivity extends AppCompatActivity {
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
DemoService.DemoBinder demoBinder = (DemoService.DemoBinder) service;
demoBinder.upload();
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
public void clickService(View view) {
switch (view.getId()) {
case R.id.btn_bind:
bindService(new Intent(this, DemoService.class), conn, BIND_AUTO_CREATE);
break;
case R.id.btn_unbind:
unbindService(conn);
break;
}
}
}
啟動 Service 時把要傳的資料放進 Intent,分別在 onStartCommand() 或 onBind() 中取出,再開新執行緒處理耗時工作。注意兩者的差異:startService() 每次自己都會觸發一次 onStartCommand();bindService() 若已綁定則只會呼叫一次 onBind()。
既然 Service 裡也要開子線程,為何不直接在 Activity 開?因為 Activity 很難控制 Thread:Activity 銷毀後,你再也拿不到先前建立的子線程實例,而且在一個 Activity 建立的子線程,另一個 Activity 也無法操作。Service 則不同,所有 Activity 都能與它關聯、操作其中的方法;即使 Activity 被銷毀,重新關聯後仍能取得原本 Binder 的實例。用 Service 承接後台任務,Activity 就能安心 finish。
需要跨進程溝通時,用 Messenger 就能搞定,不必撰寫 AIDL 檔。以下範例中,Service 在綁定時把 Messenger 送給內部的 Handler。
public class MessengerService extends Service {
private static final String TAG = "MessengerService";
private NotificationManager mNM;
/** 快取所有註冊到這個 Service 的 client */
private final ArrayList<Messenger> mClients = new ArrayList<>();
private int mValue = 0;
static final int MSG_REGISTER_CLIENT = 1;
static final int MSG_UNREGISTER_CLIENT = 2;
static final int MSG_SET_VALUE = 3;
class IncomingHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_REGISTER_CLIENT:
mClients.add(msg.replyTo);
break;
case MSG_UNREGISTER_CLIENT:
mClients.remove(msg.replyTo);
break;
case MSG_SET_VALUE:
mValue = msg.arg1;
Log.d(TAG, "handleMessage: " + mValue);
for (int i = mClients.size() - 1; i >= 0; i--) {
try {
mClients.get(i).send(
Message.obtain(null, MSG_SET_VALUE, mValue, 0));
} catch (RemoteException e) {
// client 已關閉,倒序遍歷時刪除是安全的
mClients.remove(i);
}
}
break;
default:
super.handleMessage(msg);
}
}
}
final Messenger mMessenger = new Messenger(new IncomingHandler());
@Override
public void onCreate() {
super.onCreate();
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
showNotification();
}
@Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
@Override
public void onDestroy() {
super.onDestroy();
mNM.cancel(R.string.remote_service_started);
}
private void showNotification() {
CharSequence text = getText(R.string.remote_service_started);
PendingIntent contentIntent = PendingIntent.getActivity(
this, 0, new Intent(this, ContentActivity.class), 0);
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setTicker(text)
.setWhen(System.currentTimeMillis())
.setContentTitle(getText(R.string.local_service_label))
.setContentText(text)
.setContentIntent(contentIntent)
.getNotification();
mNM.notify(R.string.remote_service_started, notification);
}
}
若希望它跑在另一個進程,在清單檔設定 android:process:
<service
android:name=".app.MessengerService"
android:process=":remote" />
client 端的寫法:
Messenger mService = null;
boolean mIsBound;
class IncomingHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MessengerService.MSG_SET_VALUE:
Log.d(TAG, "handleMessage: " + msg.arg1);
break;
default:
super.handleMessage(msg);
}
}
}
final Messenger mMessenger = new Messenger(new IncomingHandler());
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mService = new Messenger(service);
try {
Message msg = Message.obtain(null, MessengerService.MSG_REGISTER_CLIENT);
msg.replyTo = mMessenger;
mService.send(msg);
msg = Message.obtain(null, MessengerService.MSG_SET_VALUE, 202, 0);
mService.send(msg);
} catch (RemoteException e) {
// Service 已崩潰,無需額外處理
}
}
public void onServiceDisconnected(ComponentName className) {
mService = null;
}
};
void doBindService() {
bindService(new Intent(this, MessengerService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
void doUnbindService() {
if (mIsBound) {
if (mService != null) {
try {
Message msg = Message.obtain(null, MessengerService.MSG_UNREGISTER_CLIENT);
msg.replyTo = mMessenger;
mService.send(msg);
} catch (RemoteException e) {
// 忽略
}
}
unbindService(mConnection);
mIsBound = false;
}
}
Foreground Service 並不是「跑在前台」,它其實一直在後台,只是透過一個常駐通知讓使用者知道它正在運行。這也是官方推薦的做法:Service 啟動時發一個通知,例如後台播放音樂時狀態欄顯示的播放資訊。
除了自己發通知,Android 2.0(SDK level 5)以上也提供了更直接的 API:
/** * 讓 Service 成為 Foreground Service,並產生一個「正在運行」的通知。 * 預設的 Service 是後台性質,系統在回收記憶體時可以毫無顧忌地將它 kill 掉。 * 若這個 Service 掛掉會影響使用者(例如後台音樂播放器),就該用 Foreground Service 提示。 * * @param id 通知識別碼,對應 NotificationManager.notify(int, Notification) * @param notification 要顯示的通知 */ public final void startForeground(int id, Notification notification) /** * 取消 foreground 屬性,允許 Service 在低記憶體時被 kill。 * * @param removeNotification 是否同時移除先前提供給 startForeground 的通知 */ public final void stopForeground(boolean removeNotification)
呼叫 stopForeground() 會把 Service 移出前台,它的 boolean 參數決定是否也把狀態欄通知移除。這個方法本身不會停掉 Service;但反過來說,如果你停止一個正在前台運行的 Service,通知也會一起被刪除。
Service 跑在主線程,所以耗時操作還是要自己開子線程。IntentService 是 Service 的子類別,它自帶一個工作執行緒,把每個啟動請求排進佇列,一次處理一個。
用法很簡單:繼承 IntentService,實作 onHandleIntent(),這個方法接收每次啟動請求的 Intent,而且它本身就跑在子線程。
IntentService以佇列方式排入請求,再開一個 worker thread 依序處理。每個請求都在獨立的 worker thread 中完成,不會阻塞主線程。因此,如果手上有耗時任務,用IntentService往往比在 Service 裡自己開新線程更省事——預設的 worker thread 已經幫你實作好了。
使用時要留意四點:
當 Service 需要與其他應用或跨進程溝通時,就是遠程 Service 的場景。實作上可以透過 android:process 把 Service 放到獨立進程,再用 Messenger 或 AIDL 建立通訊介面。這也是為什麼前面特別強調「Service 預設不是獨立進程」——一旦跨進程,資料傳遞、生命週期與效能成本都要重新評估。
Android 開發:用 MediaRecorder 錄製影片
MediaRecorder 不只能錄音,也能錄影。整體流程與錄音幾乎一致,差別在於影片必須同時采集聲音與影像兩路資料。 因此除了呼叫 setAudioSource()
Android 4.1 移植開發中踩過的四個坑與解法
在 Android 4.1 上手機開發的過程中,累積了幾個比較典型的問題,這裡一併記錄。 問題一:只 push odex 到手機,程式無法運行 解法:修改 dalvik
Android Toast 五大用法整理:樣式、自訂版面與跨執行緒
Toast 大家都不陌生,這裡不囉嗦,直接上圖上程式碼,把常見的五種用法一次收齊。 版面配置:五顆按鈕對應五種用法 main.xml: <LinearLa
Android 小項目:Walker 歡迎頁與注冊引導頁(四)
本節要做的是 App 的「第一印象」:一個帶淡入動畫的歡迎頁,接一段可左右滑動的引導頁,最後由引導頁末屏的 Go 按鈕跳轉到登錄界面。 目標效果: 運行後先出