Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

實戰Android AIDL:打通跨進程通信的完整指南

編輯:關於 Android 程式設計

先來描述一下我們要實現的效果:在一個應用中透過點擊按鈕,去操作另一個進程裡應用的音樂播放功能。

如圖所示,當我們點擊「播放」時,系統會去遠程調用我們提供的一個service(注意,它與當前service並不在同一個應用裡),進而操作service中的音樂播放;點擊「停止」則會終止播放。如果想重新播放,必須先點「銷毀service」,再點播放按鈕。(至於為什麼要先點銷毀才能播放,純粹是為了示範遠程調用service時該如何解綁。)

在這個範例中,我們會用到一個非常重要的概念——AIDL。

AIDL(Android Interface Definition Language,Android接口描述語言)的主要作用,就是允許我們在不同的進程之間進行通信。

我們都知道,每個應用都運行在各自的進程中,而Android平台並不允許不同進程之間直接傳遞物件資料。如果非要進行跨進程通信,我們就必須把資料物件分解成一個個細小、能被操作系統理解的資料單元,再有序地通過進程邊界的檢查。

如果這一切都要自己實現,怕是能愁死一大批程式設計師。所幸Android為我們解決了這個問題,這正是AIDL誕生的原因。

AIDL是一種IDL語言,用於生成能在Android設備上兩個進程之間進行進程間通信(IPC)的程式碼。如果在一個進程中(例如Activity)要調用另一個進程中(例如Service)物件的方法,就可以用AIDL生成可序列化的參數。AIDL的IPC機制是面向介面的,有點像COM或Corba,但更加輕量級,它使用代理類在客戶端與實現端之間傳遞資料。

注意:AIDL只支援方法,不能定義靜態成員,方法也不能帶public等修飾符;AIDL的方法可以有任意類型的參數與返回值,在Java類型中,基本資料類型、String、Map、List在使用時不需要import,但為避免出錯,建議用到就導入。

使用AIDL的步驟:

服務端(提供服務):

第一步:定義一個*.aidl檔,裡面是符合AIDL語言規範的介面定義,宣告了外部應用可訪問的方法。保存該檔後,Eclipse會自動在gen資料夾下生成對應的Java介面檔,例如RemoteServiceInterface.java。

第二步:定義自己的service,並註冊到AndroidManifest.xml,例如:

 <service android:name="MyRemoteService"> <intent-filter> <action android:name="cn.com.chenzheng_java.remote"/> </intent-filter> </service> 

這裡一定要提供一個intent-filter,客戶端進程正是透過這個action訪問到服務端進程的。

我們都知道,實作自己的service時,為了讓其他應用能透過bindService與我們交互,都要實作onBind()方法,並返回一個繼承了Binder的內部類。在這裡,Eclipse自動生成的RemoteServiceInterface.java中有一個實作了Binder的內部類RemoteServiceInterface.Stub。AIDL要求我們不能再直接實作Binder類,而是去實作它提供的Stub類,同時實作介面中定義的各種服務方法。至此,服務端就和我們的aidl檔綁定在一起了。

客戶端:

第一步:客戶端要使用該服務,首先得知道服務在aidl檔中到底提供了哪些服務。所以第一步就是把aidl檔拷貝一份到客戶端程式中(注意包路徑必須與服務端保持一致,例如服務端為cn.com.chenzheng_java.remote.a.aidl,客戶端也應是這個路徑)。

第二步:要和service交互,得透過bindService方法,該方法有一個ServiceConnection類型的參數,我們的主要程式碼就寫在這個介面的實作中。

第三步:在ServiceConnection實作類的onServiceConnected(ComponentName name, IBinder service)方法中,透過remoteServiceInterface = RemoteServiceInterface.Stub.asInterface(service);這樣的寫法,就能取得遠程服務端提供的服務實例,之後便可透過它調用介面中的方法進行交互了。(關鍵在於透過*.Stub.asInterface(service);取得aidl介面的實例。)

前面說過,服務端必須提供一個intent-filter來匹配請求是否合法,所以客戶端在訪問服務時,也必須傳遞包含匹配action的Intent。

下面是完整的程式碼。遠程服務端:

RemoteServiceInterface.aidl

 package cn.com.chenzheng_java.remote; /**AIDL的語法和Interface的語法稍微有些不同, *它裡面只能有方法,並且java中的那些修飾詞如public等,在這裡是不支持的. *當我們在eclipse中添加一個以.aidl結尾的AIDL文件時,如果你的格式正確,那麼 *在gen目錄下,你就會看到系統根據你提供AIDL文件自動為你生成的相應的java類 *@author chenzheng_java */ interface RemoteServiceInterface { void startMusic(); void stopMusic(); } 

MyRemoteService.java

 package cn.com.chenzheng_java.remote; import java.io.IOException; import android.app.Service; import android.content.Intent; import android.media.MediaPlayer; import android.os.IBinder; import android.os.RemoteException; /** * @description 遠程service * @author chenzheng_java * */ public class MyRemoteService extends Service { MediaPlayer mediaPlayer; @Override public IBinder onBind(Intent intent) { return new MyBinder(); } @Override public void onCreate() { /* * MediaPlayer.create方法第一個參數實際上為context對象,這裡我們直接傳遞service給它, * 是因為service本身也是繼承了context的。 */ mediaPlayer = MediaPlayer.create(MyRemoteService.this, R.raw.aiweier); super.onCreate(); } /** * @description 這裡一定要注意,繼承的不再是Binder,而是系統自動為我們生成的 * Binder的一個內部類,叫做Stub。我們通過繼承Stub類,然後實現AIDL * 中定義的方法,便等於對接口的方法進行了具體的實現。 * @author chenzheng_java * */ private class MyBinder extends RemoteServiceInterface.Stub{ public void startMusic() throws RemoteException { mediaPlayer.start(); } public void stopMusic() throws RemoteException { mediaPlayer.stop(); try { mediaPlayer.prepare(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } } 

RemoteServiceActivity.java

 package cn.com.chenzheng_java.remote; import android.app.Activity; import android.os.Bundle; /** * 很多人不理解,這裡面基本上什麼也沒實現,為什麼還要提供呢? * 其實原因是這樣的,service代碼我們寫好了,也在配置文件中注冊了, * 這樣,手機系統就會識別了嗎?不是的哦,你至少得將該service所在的 * 應用運行一次才可以哦。要不手機怎麼知道你添加了一個service啊,對吧! * @author chenzheng_Java * */ public class RemoteServiceActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } } 

androidManifest.xml

 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="cn.com.chenzheng_java.remote" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="8" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".RemoteServiceActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name="MyRemoteService"> <intent-filter> <action android:name="cn.com.chenzheng_java.remote"/> </intent-filter> </service> </application> </manifest> 

客戶端:

activity程式碼:

 package cn.com.chenzheng_java; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import cn.com.chenzheng_java.remote.RemoteServiceInterface; /*** * @author chenzheng_java * @description 通過當前activity去調用不同進程中的遠程service */ public class LocalServiceActivity extends Activity implements OnClickListener { String ACTION_NAME = "cn.com.chenzheng_java.remote"; boolean flag = false; Button button_start ; Button button_stop ; Button button_destroy ; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.music); button_start = (Button) findViewById(R.id.button1); button_stop = (Button) findViewById(R.id.button2); button_destroy = (Button) findViewById(R.id.button3); button_start.setOnClickListener(this); button_stop.setOnClickListener(this); button_destroy.setOnClickListener(this); } RemoteServiceInterface remoteServiceInterface ; private class MyServiceConnection implements ServiceConnection{ public void onServiceConnected(ComponentName name, IBinder service) { remoteServiceInterface = RemoteServiceInterface.Stub.asInterface(service); try { Log.i("flag", flag+""); if(flag){ Log.i("通知", "已經開始唱歌"); remoteServiceInterface.startMusic(); }else{ Log.i("通知", "已經停止唱歌"); remoteServiceInterface.stopMusic(); } } catch (RemoteException e) { e.printStackTrace(); } } public void onServiceDisconnected(ComponentName name) { } } private MyServiceConnection serviceConnection = new MyServiceConnection(); public void onClick(View v) { if(v == button_start){ flag = true; Intent intent = new Intent(ACTION_NAME); /** * Context.BIND_AUTO_CREATE 當綁定service時,如果發現尚未create,那麼就先create一個,然後綁定 */ bindService(intent, serviceConnection ,Context.BIND_AUTO_CREATE); } if(v == button_stop){ Log.i("通知", "已經點擊了停止按鈕"); flag = false; Intent intent = new Intent(ACTION_NAME); bindService(intent, serviceConnection ,Context.BIND_AUTO_CREATE); try { remoteServiceInterface.stopMusic(); } catch (RemoteException e) { e.printStackTrace(); } } if(v == button_destroy){ flag = false; Intent intent = new Intent(ACTION_NAME); bindService(intent, serviceConnection ,Context.BIND_AUTO_CREATE); unbindService(serviceConnection); } } } 

music.xml

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:text="播放" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> <Button android:text="停止" android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> <Button android:text="銷毀service" android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> </LinearLayout> 

其餘未貼出的程式碼均由系統預設生成。

AIDL與傳遞物件

除了上面透過service提供音樂播放這類服務之外,我們還可以透過service把物件傳回來,你知道怎麼用嗎?先看效果:

當我們點擊「獲取」時,會從另一個執行緒的service中取得一個物件,然後把裡面的內容讀出來。

用AIDL以物件方式交互,主要步驟如下:

服務端:
第一:定義一個實體類(這裡是Beauty),以及一個服務介面aidl檔RemoteBeauty.aidl。這裡要注意,把自訂實體類引用到aidl中時需要import導入套件,但你會發現即使導入了仍提示找不到,這時你要做的是建立一個以實體類名稱命名的aidl檔(如Beauty.aidl),並在其中寫上一句parcelable Beauty。

第二:開始編寫Beauty,這裡一定要實作Parcelable介面(這是Android提供的一個比Serializable效率更高的序列化介面)。此外,Beauty內部一定要宣告一個public static final Parcelable.Creator<T> CREATOR物件(除了那個T代表實體類之外,其他都不能改)。

第三:在AndroidManifest.xml中註冊service,並定義好訪問該service的action字串。

客戶端:
客戶端這邊要簡單很多,但要特別注意:必須把實體類與aidl檔都拷貝過來,而且路徑要完全一致!!

Beauty.java

 package cn.com.chenzheng_java.service; import android.os.Parcel; import android.os.Parcelable; /** * * @author chenzheng_java * @description Parcelable是android提供的一個比serializable效率更高的序列號接口 * 這裡必須要繼承Parcelable哦,不序列號怎麼可以傳遞……對吧?! * 在實體類我們要做兩件重要的事情: * 第一:實現Parcelable接口 * 第二:定義一個Parcelable.Creator類型的CREATOR對象 * 第三:要提供一個Beauty.aidl文件,其中內容為parcelable Beauty,定義了之後,在其他aidl文件中引用Beauty時便不會提示出錯了。 * @since 2011/03/18 * */ public class Beauty implements Parcelable { String name ; int age ; String sex ; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } @Override public int describeContents() { return 0; } /** * 將對象序列號 * dest 就是對象即將寫入的目的對象 * flags 有關對象序列號的方式的標識 * 這裡要注意,寫入的順序要和在createFromParcel方法中讀出的順序完全相同。例如這裡先寫入的為name, * 那麼在createFromParcel就要先讀name */ @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(name); dest.writeInt(age); dest.writeString(sex); } /** * 在想要進行序列號傳遞的實體類內部一定要聲明該常量。常量名只能是CREATOR,類型也必須是 * Parcelable.Creator<T> */ public static final Parcelable.Creator<Beauty> CREATOR = new Creator<Beauty>() { /** * 創建一個要序列號的實體類的數組,數組中存儲的都設置為null */ @Override public Beauty[] newArray(int size) { return new Beauty[size]; } /*** * 根據序列號的Parcel對象,反序列號為原本的實體對象 * 讀出順序要和writeToParcel的寫入順序相同 */ @Override public Beauty createFromParcel(Parcel source) { String name = source.readString(); int age = source.readInt(); String sex = source.readString(); Beauty beauty = new Beauty(); beauty.setName(name); beauty.setAge(age); beauty.setSex(sex); return beauty; } }; } 

RemoteService.java

 package cn.com.chenzheng_java.service; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; /** * * @author chenzheng_java * @description 提供服務的service * */ public class RemoteService extends Service { @Override public IBinder onBind(Intent intent) { Log.i("通知", "執行了OnBind"); return new MyBinder(); } private class MyBinder extends RemoteBeauty.Stub{ @Override public Beauty getBeauty() throws RemoteException { Beauty beauty = new Beauty(); beauty.setName("feifei"); beauty.setAge(21); beauty.setSex("female"); return beauty; }} } 

ServiceActivity.java

 package cn.com.chenzheng_java.service; import android.app.Activity; import android.os.Bundle; /** * @description 進程之間對象數據的傳遞 * @author chenzheng_java * */ public class ServiceActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } } 

Beauty.aidl

 parcelable Beauty; 

RemoteBeauty.aidl

 package cn.com.chenzheng_java.service; import cn.com.chenzheng_java.service.Beauty; interface RemoteBeauty { Beauty getBeauty(); } 

manifest.xml

 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="cn.com.chenzheng_java.service" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="8" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".ServiceActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- service開始 --> <service android:name="RemoteService"> <intent-filter> <action android:name="cn.com.chenzheng_java.remote2"/> </intent-filter> </service> <!-- service結束 --> </application> </manifest> 

客戶端:

ClientActivity.java

 package cn.com.chenzheng_java.client; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import cn.com.chenzheng_java.service.Beauty; import cn.com.chenzheng_java.service.RemoteBeauty; public class ClientActivity extends Activity implements OnClickListener { TextView textView ; Button button ; String actionName = "cn.com.chenzheng_java.remote2"; RemoteBeauty remoteBeauty; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); textView = (TextView) findViewById(R.id.textView1); button = (Button) findViewById(R.id.button1); button.setOnClickListener(this); } private class MyServiceConnection implements ServiceConnection{ @Override public void onServiceConnected(ComponentName name, IBinder service) { Log.i("通知", "鏈接成功!"); remoteBeauty = RemoteBeauty.Stub.asInterface(service); try { Beauty beauty = remoteBeauty.getBeauty(); textView.setText("美女 姓名:"+beauty.getName()+" 年齡:"+beauty.getAge() +" 性別:"+beauty.getSex()); } catch (RemoteException e) { e.printStackTrace(); } } @Override public void onServiceDisconnected(ComponentName name) { } } MyServiceConnection connection = new MyServiceConnection(); @Override public void onClick(View v) { Intent intent = new Intent(actionName); bindService(intent, connection, Context.BIND_AUTO_CREATE); } } 

另外,Beauty.java與RemoteBeauty.aidl都是從服務端拷貝過來的。

如果你希望service在系統開機時自動啟動,可以在manifest中加上這樣的配置:

 <receiver android:name=".StartBroadcastReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"/> </intent-filter> </receiver> 
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved