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

深入解析 Android AIDL:輕鬆實現跨進程通信(IPC)

編輯:關於 Android 程式設計

前言

在 Android 系統裡,每一個應用都運行在各自獨立的進程之中,擁有彼此隔離的內存空間。然而,現實開發中我們常常會遇到這樣的需求:讓自己的應用與其他應用交換數據、互相調用。問題在於,Java 本身並不允許跨進程共享內存,數據無法直接傳遞。為了解決這一難題,Android 提供了 AIDL(Android Interface Definition Language)這套機制來完成進程間通信(IPC)。

Android 官方對 AIDL 的定義是這樣描述的:AIDL 與你接觸過的其他 IDL 類似,它讓你定義一份客戶端與服務端共同遵守的編程接口,雙方通過 IPC 進行交流。由於 Android 上一個進程通常無法直接訪問另一個進程的內存,它們必須先把對象拆解成操作系統能夠理解的基本類型,再通過封送(marshalling)跨越這道邊界。封送代碼寫起來枯燥又繁瑣,而 Android 用 AIDL 替我們自動完成了這一切。

適用場景

並不是所有情況都需要動用 AIDL。當且僅當你需要讓來自不同應用的客戶端訪問你的 Service 進行 IPC,並且希望在 Service 內部處理多線程問題時,AIDL 才是必要的選擇。

Android 官方同樣給出了提醒:

Note: Using AIDL is necessary only if you allow clients from different applications to access your service for IPC and want to handle multithreading in your service. If you do not need to perform concurrent IPC across different applications, you should create your interface by implementing a Binder or, if you want to perform IPC, but do not need to handle multithreading, implement your interface using a Messenger. Regardless, be sure that you understand Bound Services before implementing an AIDL.

線程阻塞與安全問題

Before you begin designing your AIDL interface, be aware that calls to an AIDL interface are direct function calls. You should not make assumptions about the thread in which the call occurs. What happens is different depending on whether the call is from a thread in the local process or a remote process. Specifically:

Calls made from the local process are executed in the same thread that is making the call. If this is your main UI thread, that thread continues to execute in the AIDL interface. If it is another thread, that is the one that executes your code in the service. Thus, if only local threads are accessing the service, you can completely control which threads are executing in it (but if that is the case, then you shouldn't be using AIDL at all, but should instead create the interface by implementing a Binder).Calls from a remote process are dispatched from a thread pool the platform maintains inside of your own process. You must be prepared for incoming calls from unknown threads, with multiple calls happening at the same time. In other words, an implementation of an AIDL interface must be completely thread-safe.The oneway keyword modifies the behavior of remote calls. When used, a remote call does not block; it simply sends the transaction data and immediately returns. The implementation of the interface eventually receives this as a regular call from the Binder thread pool as a normal remote call. If oneway is used with a local call, there is no impact and the call is still synchronous.

定義 AIDL 接口

你需要用 Java 的語法來編寫 AIDL 接口,並把它保存為副檔名是 .aidl 的文件。這些 .aidl 文件必須同時放在主應用與客戶端應用的 src 目錄之下。當工程中包含 .aidl 文件時,Android SDK 工具會依據其定義,在應用的 gen/ 目錄中自動生成對應的 IBinder 接口。主應用的 Service 需要實現這個 IBinder 接口,客戶端便能綁定到該 Service,並通過 IBinder 對象完成 IPC。

AIDL 實戰

把上面的理論吃透之後,就可以動手實現 AIDL 接口、完成進程間通信了。為了便於理解,先看一下整個工程的目錄結構:

1. 創建 .aidl 文件

你必須按照 Java 的語法結構來編寫 .aidl 文件,而且每一個 .aidl 文件只能定義一個接口。

AIDL 默認支持以下數據類型:

All primitive types in the Java programming language (such as int, long, char, boolean, and so on)StringCharSequenceList All elements in the List must be one of the supported data types in this list or one of the other AIDL-generated interfaces or parcelables you've declared. A List may optionally be used as a generic class (for example, List). The actual concrete class that the other side receives is always an ArrayList, although the method is generated to use the List interface.Map All elements in the Map must be one of the supported data types in this list or one of the other AIDL-generated interfaces or parcelables you've declared. Generic maps, (such as those of the form Map are not supported. The actual concrete class that the other side receives is always a HashMap, although the method is generated to use the Map interface.

如果你想使用上述以外的其他類型對象,就必須通過 import 語句導入,即使它和你在 .aidl 文件中定義的包名完全一致也一樣。

下面是一個 .aidl 示例文件:

 // IRemoteService.aidl package com.ricky.android.aidl.protocal; import com.ricky.android.aidl.model.Student; import com.ricky.android.aidl.model.Address; // Declare any non-default types here with import statements /** Example service interface */ interface IRemoteService { /** Request the process ID of this service, to do evil things with it. */ int getPid(); /** Demonstrates some basic types that you can use as parameters * and return values in AIDL. */ int sum(int number, String process); void say(int time, String message); Student getStudent(int id); List getAddress(int id); }

AIDL 接口需要傳遞 Student 對象和 Address 對象,這兩者都實現了 Parcelable 接口,代碼分別如下:

Student.java

 package com.ricky.android.aidl.model; import java.util.List; import android.os.Parcel; import android.os.Parcelable; public class Student implements Parcelable { private int id; private String name; private List hobbies; private Address addr; public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { @Override public Student createFromParcel(Parcel in) { // TODO Auto-generated method stub return new Student(in); } @Override public Student[] newArray(int size) { // TODO Auto-generated method stub return new Student[size]; } }; public Student(){ } protected Student(Parcel in){ readFromParcel(in); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List getHobbies() { return hobbies; } public void setHobbies(List hobbies) { this.hobbies = hobbies; } public Address getAddr() { return addr; } public void setAddr(Address addr) { this.addr = addr; } @Override public int describeContents() { // TODO Auto-generated method stub return 0; } @Override public void writeToParcel(Parcel out, int flags) { out.writeInt(id); out.writeString(name); out.writeList(hobbies); out.writeParcelable(addr, 0); } @SuppressWarnings(unchecked) public void readFromParcel(Parcel in) { id = in.readInt(); name = in.readString(); hobbies = in.readArrayList(getClass().getClassLoader()); addr = in.readParcelable(getClass().getClassLoader()); } @Override public String toString() { return Student [id= + id + , name= + name + , hobbies= + hobbies + , addr= + addr + ]; } } 

Address.java

 package com.ricky.android.aidl.model; import android.os.Parcel; import android.os.Parcelable; public class Address implements Parcelable { private String province; private String city; private String district; private String street ; private int postcode; public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { @Override public Address createFromParcel(Parcel in) { return new Address(in); } @Override public Address[] newArray(int size) { return new Address[size]; } }; public Address(){ } public Address(Parcel in){ readFromParcel(in); } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getDistrict() { return district; } public void setDistrict(String district) { this.district = district; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public int getPostcode() { return postcode; } public void setPostcode(int postcode) { this.postcode = postcode; } @Override public String toString() { return Address [province= + province + , city= + city + , district= + district + , street= + street + , postcode= + postcode + ]; } @Override public int describeContents() { // TODO Auto-generated method stub return 0; } @Override public void writeToParcel(Parcel out, int flags) { out.writeString(province); out.writeString(city); out.writeString(district); out.writeString(street); out.writeInt(postcode); } public void readFromParcel(Parcel in) { province = in.readString(); city = in.readString(); district = in.readString(); street = in.readString(); postcode = in.readInt(); } } 


特別注意:.aidl 文件必須存放在與其包名一致的目錄之下,例如本例中的 package com.ricky.android.aidl.protocal;

2. 實現 IBinder 接口

 package com.ricky.android.aidl.protocal; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.ricky.android.aidl.model.Address; import com.ricky.android.aidl.model.Student; import com.ricky.android.aidl.util.Logger; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.os.Process; import android.os.RemoteException; public class MyService extends Service { private static final String TAG = MyService.class.getSimpleName(); @Override public void onCreate() { Logger.i(TAG, onCreate); super.onCreate(); } @Override public IBinder onBind(Intent intent) { Logger.i(TAG, onBind); return mBinder; } private final IRemoteService.Stub mBinder = new IRemoteService.Stub() { @Override public int getPid() throws RemoteException { return Process.myPid(); } @Override public int sum(int number, String process) throws RemoteException { Logger.i(TAG, call sum,number=+number+**process=+process); int sum = 0; for(int i=0;i getAddress(int id) throws RemoteException { List list = new ArrayList(); Address addr = new Address(); addr.setProvince(北京); addr.setCity(北京市); addr.setDistrict(朝陽區); addr.setStreet(香河園); addr.setPostcode(100010); list.add(addr); return list; } }; }

在 Manifest 清單文件中注冊 Service

            


至此,AIDL 的服務端就完成了。客戶端只要綁定 MyService 並拿到 IBinder 對象,就能實現 IPC。

實現 AIDL 接口時,還有幾條規則值得牢記:

There are a few rules you should be aware of when implementing your AIDL interface: Incoming calls are not guaranteed to be executed on the main thread, so you need to think about multithreading from the start and properly build your service to be thread-safe.By default, RPC calls are synchronous. If you know that the service takes more than a few milliseconds to complete a request, you should not call it from the activity's main thread, because it might hang the application (Android might display an Application is Not Responding dialog)—you should usually call them from a separate thread in the client.No exceptions that you throw are sent back to the caller.

3. 暴露接口給客戶端調用

3.1 新建客戶端 Application,結構如下:

3.2 引入 AIDL 文件以及相關的類,直接從服務端 copy 過來即可。

3.3 綁定遠程 Service

 package com.ricky.android.aidlclient; import java.util.List; import com.ricky.android.aidl.model.Address; import com.ricky.android.aidl.model.Student; import com.ricky.android.aidl.protocal.IRemoteService; import com.ricky.android.aidlclient.util.Logger; 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.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity implements OnClickListener { protected static final String TAG = null; private Button bt_bind; private IRemoteService mIRemoteService; private Button bt_unbind; private TextView tv_status; private boolean isBind; private Button bt_call; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(); setListener(); processLogic(); } private void findViewById() { bt_bind = (Button) findViewById(R.id.bt_bind); bt_unbind = (Button) findViewById(R.id.bt_unbind); bt_call = (Button) findViewById(R.id.bt_call); tv_status = (TextView) findViewById(R.id.tv_status); } private void setListener() { bt_bind.setOnClickListener(this); bt_unbind.setOnClickListener(this); bt_call.setOnClickListener(this); } private void processLogic() { tv_status.setText(Unbinding); } private ServiceConnection mConnection = new ServiceConnection() { // Called when the connection with the service is established @Override public void onServiceConnected(ComponentName name, IBinder service) { Logger.i(TAG, onServiceConnected); // Following the example above for an AIDL interface, // this gets an instance of the IRemoteInterface, which we can use to call on the service mIRemoteService = IRemoteService.Stub.asInterface(service); } // Called when the connection with the service disconnects unexpectedly @Override public void onServiceDisconnected(ComponentName name) { Logger.i(TAG, onServiceDisconnected); mIRemoteService = null; } }; @Override public void onClick(View v) { switch (v.getId()) { case R.id.bt_bind: bindService(new Intent(com.ricky.android.aidl), mConnection, Context.BIND_AUTO_CREATE); isBind = true; tv_status.setText(Binding); break; case R.id.bt_unbind: if (isBind) { try { unbindService(mConnection); isBind = false; tv_status.setText(Unbinding); } catch (Exception e) { e.printStackTrace(); } } break; case R.id.bt_call: if (isBind) { try { int pid = mIRemoteService.getPid(); Logger.i(TAG, call mIRemoteService's getPid pid=+pid); mIRemoteService.say(1, hello world); int sum = mIRemoteService.sum(100, ricky); Logger.i(TAG, call mIRemoteService's sum result=+sum); Student stu = mIRemoteService.getStudent(3); Logger.i(TAG, call mIRemoteService's getStudent stu=+stu); List list = mIRemoteService.getAddress(2); Logger.i(TAG, call mIRemoteService's getAddress list=+list); } catch (RemoteException e) { e.printStackTrace(); } }else{ Logger.i(TAG, not bind remote service); Toast.makeText(getApplicationContext(), not bind remote service,Toast.LENGTH_SHORT).show(); } break; default: break; } } @Override protected void onDestroy() { if (isBind) { try { unbindService(mConnection); isBind = false; tv_status.setText(Unbinding); } catch (Exception e) { e.printStackTrace(); } } super.onDestroy(); } } 


通過 Context.bindService(Intent service, ServiceConnection conn, int flags) 方法綁定遠程 Service,再通過 IRemoteService com.ricky.android.aidl.protocal.IRemoteService.Stub.asInterface(IBinder obj) 方法拿到 IRemoteService 對象,此時客戶端就可以通過它進行 IPC 了。

activity_main.xml

  

運行界面如下:


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved