編輯:Android 開發實例
上一篇我們已經把 Service 的幾個重點都談過了:基本用法、與 Activity 通訊、銷毀時機、Service 與 Thread 的關係,以及如何建立前台 Service。這些內容大致涵蓋了日常開發中會用到的 Service 技術。
不過還有一個更高階的用法沒講,那就是遠程 Service。用了它,甚至可以實現 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 中另開執行緒去跑耗時任務,這樣就能避免 ANR。
那麼,如果把 MyService 改成遠程 Service,還會不會 ANR?試試看。
轉換非常簡單,只要在註冊 Service 時把 android:process 指定為 :remote:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.servicetest"
android:versionCode="1"
android:versionName="1.0" >
......
<service
android:name="com.example.servicetest.MyService"
android:process=":remote" >
</service>
</manifest>
重新執行並點擊 Start Service,你會看到控制台立刻印出 onCreate() executed,主畫面完全沒有卡住,也不會 ANR。大約一分鐘後,onStartCommand() executed 才被印出來。
原因很直觀:改用遠程 Service 之後,MyService 已經跑在另一個進程裡,被阻塞的只是那個進程的主執行緒,跟目前的應用程式無關。
為了證實這件事,我們在 MainActivity 與 MyService 的 onCreate() 各加一行日誌,印出各自的進程 id:
Log.d("TAG", "process id is " + Process.myPid());
再次執行並點擊 Start Service,可以看到兩者的進程 id 完全不同,而且連應用程式包名也不一樣——MyService 那條日誌的包名後面還帶著 :remote 標識。
既然這麼神奇,那乾脆把所有 Service 都改成遠程的,還省得開執行緒?並不然。遠程 Service 不但不好用,甚至可以說相當難用。一般情況下,能不用就盡量不要用。
把 onCreate() 裡的 sleep 移除,重新執行後點擊 Bind Service——程式直接崩潰了。為什麼 Start Service 不會崩,Bind Service 就會?因為 Bind Service 的點擊事件裡會讓 MainActivity 與 MyService 建立關聯,而現在兩者已經分屬不同進程,傳統的建立關聯方式自然行不通。
那要怎麼讓 Activity 與一個遠程 Service 建立關聯?答案就是 AIDL 所支撐的跨進程通信(IPC)。
AIDL(Android Interface Definition Language,Android 介面定義語言)的作用,是讓某個 Service 能與多個應用程式元件進行跨進程通訊,从而实现多個應用共享同一個 Service。
第一步,新建一個 AIDL 檔,在裡面定義 Activity 需要與 Service 溝通的方法。建立 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;
}
};
}
這裡實作了 MyAIDLService.Stub,覆寫 toUpperCase()(把字串轉成全大寫)與 plus()(兩整數相加),然後在 onBind() 中把 Stub 的實例傳回去。之所以能這樣寫,是因為 Stub 本身就是 Binder 的子類。
第三步,修改 MainActivity:
public class MainActivity extends Activity implements OnClickListener {
private Button startService;
private Button stopService;
private Button bindService;
private Button unbindService;
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("hello world");
Log.d("TAG", "result is " + result);
Log.d("TAG", "upperStr is " + upperStr);
} catch (RemoteException e) {
e.printStackTrace();
}
}
};
......
}
改動集中在 ServiceConnection 裡:先用 MyAIDLService.Stub.asInterface() 把傳入的 IBinder 轉成 MyAIDLService 物件,之後就能呼叫 aidl 檔中定義的所有方法了。範例中先呼叫 plus(3, 5),再呼叫 toUpperCase("hello world"),最後把結果印出來。
重新執行並點擊 Bind Service,日誌中就能看到計算與轉換後的結果。跨進程通信確實成功了——在一個進程中,我們呼叫到了另一個進程裡的方法。
不過你大概也看出来了,目前這個示範並沒有什麼實質作用,因為那只是同一個應用裡的 Activity 去呼叫自己 Service 的方法。跨進程通信的真正價值,在於讓「應用 A」能存取「應用 B」的 Service,達到共享 Service 的目的。
我們都知道,要讓 Activity 與 Service 建立關聯,需要呼叫 bindService() 並傳入 Intent:
Intent bindIntent = new Intent(this, MyService.class); bindService(bindIntent, connection, BIND_AUTO_CREATE);
問題在這裡:建構 Intent 時我們用的是 MyService.class 來指定目標,但另一個應用程式裡根本沒有 MyService 這個類別。這時就必須改用隱式 Intent。
修改 ServiceTest 的 AndroidManifest.xml,幫 MyService 加上一個 action:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.servicetest"
android:versionCode="1"
android:versionName="1.0" >
......
<service
android:name="com.example.servicetest.MyService"
android:process=":remote" >
<intent-filter>
<action android:name="com.example.servicetest.MyAIDLService"/>
</intent-filter>
</service>
</manifest>
這代表 MyService 現在可以回應帶有 com.example.servicetest.MyAIDLService 這個 action 的 Intent。重新執行一次,遠程 Service 端的工作就完成了。
接著新建一個 Android 專案,命名為 ClientTest,我們要在這裡遠程呼叫 MyService 的方法。
第一步,把 MyAIDLService.aidl 從 ServiceTest 複製過來,注意必須連同原本的套件路徑一起複製,完成後的專案結構才會正確。
第二步,在 activity_main.xml 中放一個 Bind Service 按鈕:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/bind_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Bind Service" />
</LinearLayout>
第三步,在 MainActivity 中加入與 MyService 建立關聯的程式碼:
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 的 MainActivity 幾乎完全相同,唯一的差別是建立關聯時改用隱式 Intent,把 action 指定為 com.example.servicetest.MyAIDLService。
關聯建立之後,ClientTest 一樣呼叫 plus() 與 toUpperCase(),遠程的 MyService 會處理傳入的參數並回傳結果,再由客戶端印出來。
執行 ClientTest 並點擊 Bind Service,就會去跟遠程的 MyService 建立關聯,LogCat 中的輸出顯示跨進程通信已經完整跑通。
由於是在不同進程之間傳遞資料,Android 對這類資料的格式支援相當有限,基本上只能傳 Java 的基本資料型別、字串、List 或 Map。
如果想傳一個自訂的類別怎麼辦?那就必須讓該類別實作 Parcelable 介面,並且為它另外定義一個同名的 AIDL 檔。這部分並不複雜,而且與 Service 本身關係不大,有興趣的朋友可以自行查閱資料。
結合上下兩篇,這就是關於 Service 你所需知道的一切。
用 ViewPager 打造自動輪播廣告板:完整源碼分享
android-support-v4.jar 是 Google 官方為相容低版本裝置所提供的套件,裡面包含了原本只有 Android 3.0 以上才支援的 API,而 V
Android 多語言應用:本地化字串與 values-it 資料夾怎麼用
一支上架的 App,很可能同時被台灣、日本、德國的使用者打開。要讓每個人都看得懂,App 就得依裝置的語言環境,換上對應的文字、數字與格式。這件事在 Android 裡稱
Android 自訂 Toast:讓提示訊息符合 App 的視覺風格
系統預設的 Toast 簡潔好用,一行 makeText 就能搞定。問題是它長得實在太「系統」了,放在一個講究視覺設計的 App 裡總顯得格格不入。好在 Toast 的樣
Unity3D 發布 APK 並在 Android 模擬器運行的步驟
Unity3D 專案要發布為 Android APK 並在模擬器中執行,需要完成 Java 環境、Android SDK、Unity 發布設定與 ADB 安裝等流程。環境