編輯:關於 Android 程式設計
先釐清一個常被誤解的前提:Service 其實是運行在主線程裡的。也就是說,如果你直接在 Service 中處理耗時邏輯,一樣會觸發 ANR。
把上一篇文章的 ServiceTest 專案拿出來,在 MyService.onCreate() 中讓線程睡 60 秒:
public class MyService extends Service {
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate() executed");
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
重新執行後,點一下 Start Service 或 Bind Service,畫面立刻卡住,什麼都點不動,過一會兒就跳出 ANR 提示框。

標準解法是在 Service 中另開線程執行耗時任務。不過本文要談的是另一條路:遠端 Service。
做法出乎意料地簡單,只要在 Manifest 註冊時加上 android:process 屬性並指定一個行程名稱即可:
<service
android:name="com.example.servicetest.MyService"
android:process=":remote" />
重新執行,點 Start Service,你會看到控制台立刻印出 onCreate() executed,主界面完全不卡,也不出現 ANR;大約一分鐘後才印出 onStartCommand() executed。
原因很直接:改用遠端 Service 之後,MyService 已經跑在另一個行程裡,睡眠只會阻塞那個行程的主線程,與目前的應用程式無關。
想驗證的話,在 MainActivity 與 MyService 的 onCreate() 各加一行日誌:
Log.d("TAG", "process id is " + Process.myPid());
再次執行並點下按鈕:

可以看到不僅行程 ID 不同,連應用程式包名也不一樣了——MyService 那條日誌的包名後面還多了 :remote 標識。
既然這麼有效,是不是乾脆把所有 Service 都改成遠端的?並不建議。遠端 Service 非但不好用,甚至可以說相當難用,能不用就盡量不用。
把剛剛的 sleep 移除,重新執行並點 Bind Service,你會發現程式直接崩潰。為什麼 Start Service 沒事,Bind Service 卻炸了?因為 Bind Service 的目的是讓 Activity 與 Service 建立關聯,但此時兩者已經分屬不同行程,傳統的 bindService 直接綁定方式不再適用。
要讓 Activity 與遠端 Service 溝通,就必須使用 AIDL 進行跨進程通訊(IPC)。
AIDL(Android Interface Definition Language)是 Android 介面定義語言,它讓某個 Service 能與多個應用程式元件跨進程通訊,進而實現「多個應用程式共用同一個 Service」的效果。
先建立一個 AIDL 檔,在其中宣告 Activity 需要呼叫的方法。新增 MyAIDLService.aidl:
package com.example.servicetest;
interface MyAIDLService {
int plus(int a, int b);
String toUpperCase(String str);
}
存檔後,gen 目錄下會自動產生對應的 Java 檔案。

接著在 MyService 中實作這個介面:
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
MyAIDLService.Stub mBinder = new Stub() {
@Override
public String toUpperCase(String str) throws RemoteException {
if (str != null) {
return str.toUpperCase();
}
return null;
}
@Override
public int plus(int a, int b) throws RemoteException {
return a + b;
}
};
}
這裡之所以能在 onBind() 直接回傳 Stub 的實作,是因為 Stub 本身就是 Binder 的子類。
最後別忘了在 Manifest 為這個 Service 加上 action,讓其他應用程式能用隱式 Intent 找到它:
<service
android:name="com.example.servicetest.MyService"
android:process=":remote">
<intent-filter>
<action android:name="com.example.servicetest.MyAIDLService" />
</intent-filter>
</service>
這代表 MyService 能回應帶有 com.example.servicetest.MyAIDLService 這個 action 的 Intent。
如果 Activity 與 Service 在同一個 App 內,程式碼幾乎和一般 Service 相同,只在 onServiceConnected 中多了一步介面轉換:
private MyAIDLService myAIDLService;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) { }
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
myAIDLService = MyAIDLService.Stub.asInterface(service);
try {
int result = myAIDLService.plus(3, 5);
String upperStr = myAIDLService.toUpperCase("helloworld");
Log.d("TAG", "result is " + result);
Log.d("TAG", "upperStr is " + upperStr);
} catch (RemoteException e) {
e.printStackTrace();
}
}
};
MyAIDLService.Stub.asInterface() 把傳入的 IBinder 轉成 MyAIDLService 物件,之後就能呼叫 AIDL 檔中宣告的所有方法。
換成另一個 App 來綁定時,關鍵差異是:對方沒有 MyService 這個類別,因此必須使用隱式 Intent。
版面很簡單,一顆 Bind Service 按鈕:
<Button
android:id="@+id/bind_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="BindService" />
MainActivity:
public class MainActivity extends Activity {
private MyAIDLService myAIDLService;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) { }
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
myAIDLService = MyAIDLService.Stub.asInterface(service);
try {
int result = myAIDLService.plus(50, 50);
String upperStr = myAIDLService.toUpperCase("comes from ClientTest");
Log.d("TAG", "result is " + result);
Log.d("TAG", "upperStr is " + upperStr);
} catch (RemoteException e) {
e.printStackTrace();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bindService = (Button) findViewById(R.id.bind_service);
bindService.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("com.example.servicetest.MyAIDLService");
bindService(intent, connection, BIND_AUTO_CREATE);
}
});
}
}
這段程式碼和 ServiceTest 中的幾乎一模一樣,唯一的差別是 Intent 的建構方式——用 action 字串而非 MyService.class。
執行 ClientTest,點下 Bind Service,就會跨應用程式與遠端 MyService 建立關聯:

看到這裡,跨進程通訊就算完整跑通了。
由於是在不同行程之間傳遞資料,Android 對可傳遞的型別支援相當有限,基本上只涵蓋 Java 基本型別、字串、List 與 Map。如果想傳遞自訂類別,就必須讓該類別實作 Parcelable 介面,並為它另外定義一個同名的 AIDL 檔。這部分並不複雜,且與 Service 本身關係不大,有興趣可以自行查閱資料。
把這篇與上一篇合起來看,大概就是關於 Service 你該知道的全部了。
Android 斷點下載實作教學:用 SQLite 記錄進度並支援多執行緒續傳
近期專案裡需要實作斷點下載——同一個檔案可以分多次下載、中途可以暫停,之後再從上次的位置接著跑。這是大多數具備離線快取功能的 App 都必須具備的能力。本文以 SQLit
Android Studio 調試技巧全解:從斷點到求值
Android Studio 已經是開發 Android 的主力工具,用熟了非常順手。而排查問題、定位並修復 Bug 是我們的看家本領。工欲善其事,必先利其器——和 Ec
Android Window、PhoneWindow、WindowManager 與 Activity 學習心得(第一彈)
閱讀本文前,你需要先理解 Context 上下文環境與 Window 窗口的準確含義。那麼,我們就從 Activity 的啟動開始講起。 Activity 的啟動流程
Android 開發:輕鬆讀取電池各項資訊
想讓 App 顯示目前電池的電量、電壓、溫度與類型嗎?Android 提供了 ACTION_BATTERY_CHANGED 這個系統廣播,透過自訂的 BroadcastR