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

Android AIDL 入門:從 Parcelable 到跨進程 Demo

編輯:關於 Android 程式設計

AIDL 全名是 Android Interface Definition Language,顧名思義,它是一種用來定義介面的語言。Android 提供 AIDL 的核心目的,是解決跨進程通訊(IPC)的問題。

什麼時候該用 AIDL?

從功能定位來看,AIDL 的 utama 應用場景就是 IPC。同一進程內的 client 與 service 當然也能靠 AIDL 定義介面來溝通,但這並沒有發揮它的價值。實務上的判斷可以濃縮成三條:

  • 不需要 IPC:直接繼承 Binder 類實作用戶端與伺服器端的通訊即可。
  • 需要 IPC,但不需要處理多執行緒:用 Messenger 就好。Messenger 保證訊息是序列處理的,而它內部其實也是靠 AIDL 實作的。
  • 需要 IPC,且伺服器端必須併發處理多個請求:這才是 AIDL 真正必要的場合。

基本使用步驟

  1. 撰寫 .aidl 檔,定義需要的介面。
  2. 實作該介面。
  3. 把介面暴露出來給用戶端呼叫。

以下在 Android Studio 建一個專案實際跑一遍。

一、建立 AIDL 檔

建立完成後,Android Studio 已經先給了一份範例:

// IMyAidlInterface.aidl
package com.example.aidltest;

// Declare any non-default types here with import statements
interface IMyAidlInterface {
	/**
	 * Demonstrates some basic types that you can use as parameters
	 * and return values in AIDL.
	 */
	void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
			double aDouble, String aString);
}

AIDL 支援的資料型別

  • 所有基本型別(int、float、long、boolean、double 等)
  • String
  • CharSequence
  • List
  • Map

如果要傳自訂型別,該類別必須實作 Parcelable 介面才能跨進程傳遞。

二、自訂 Parcelable 型別

先定義一個 HelloMsg 類別:

public class HelloMsg implements Parcelable {

	private String name;
	private int age;

	public HelloMsg(String name, int age) {
		this.name = name;
		this.age = age;
	}

	protected HelloMsg(Parcel in) {
		name = in.readString();
		age = in.readInt();
	}

	public static final Creator<HelloMsg> CREATOR = new Creator<HelloMsg>() {
		@Override
		public HelloMsg createFromParcel(Parcel in) {
			return new HelloMsg(in);
		}

		@Override
		public HelloMsg[] newArray(int size) {
			return new HelloMsg[size];
		}
	};

	@Override
	public int describeContents() {
		return 0;
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		dest.writeString(name);
		dest.writeInt(age);
	}

	@Override
	public String toString() {
		return "HelloMsg{" +
				"name='" + name + '\'' +
				", age=" + age +
				'}';
	}
}

有了 HelloMsg.java 之後,還需要一個對應的 AIDL 宣告檔。在 src 上按右鍵,新增一個名為 IHelloMsgInterface.aidl 的檔案:

// IHelloMsgInterface.aidl
package com.example.aidltest;

parcelable HelloMsg;

注意這裡的 parcelable 首字母是小寫的,這是 AIDL 一個容易踩到的特殊寫法。

接著修改 IMyAidlInterface.aidl,改用自訂型別:

// IMyAidlInterface.aidl
package com.example.aidltest;

import com.example.aidltest.HelloMsg;

interface IMyAidlInterface {
	HelloMsg sayHello();
}

即使 IMyAidlInterface.aidl 與 IHelloMsgInterface.aidl 位於同一個 package 底下,這裡的 import 仍然是必須的——這也是 AIDL 的另一個特殊之處。

實務提醒:build 之後可能會報錯,把 IHelloMsgInterface.aidl 重新命名為 HelloMsg.aidl(檔名與宣告的型別同名)即可解決。

三、看懂自動產生的 Binder 骨架

build 成功後,會在 build/generated/source/aidl/debug 底下產生 IMyAidlInterface.java。花點時間讀一遍這個檔案,對理解 Android Binder 機制很有幫助:

public interface IMyAidlInterface extends android.os.IInterface {

	/** Local-side IPC implementation stub class. */
	public static abstract class Stub extends android.os.Binder
			implements com.example.aidltest.IMyAidlInterface {

		private static final java.lang.String DESCRIPTOR =
				"com.example.aidltest.IMyAidlInterface";

		/** Construct the stub at attach it to the interface. */
		public Stub() {
			this.attachInterface(this, DESCRIPTOR);
		}

		/**
		 * Cast an IBinder object into an IMyAidlInterface interface,
		 * generating a proxy if needed.
		 */
		public static com.example.aidltest.IMyAidlInterface
				asInterface(android.os.IBinder obj) {
			if ((obj == null))
				return null;

			android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
			if (((iin != null) &&
					(iin instanceof com.example.aidltest.IMyAidlInterface))) {
				return ((com.example.aidltest.IMyAidlInterface) iin);
			}
			return new com.example.aidltest.IMyAidlInterface.Stub.Proxy(obj);
		}
	}
}

這裡有個內部類 Stub,同時繼承系統的 Binder 類並實作 IMyAidlInterface 介面。另外還提供了 asInterface():它接受一個遠端 Binder 物件,把它轉成 Stub 對應的介面物件後回傳。建構子中呼叫 attachInterface 把服務物件與 DESCRIPTOR 綁在一起;asInterface 則透過 queryLocalInterface 查詢——若對方在同一進程就直接回傳本地物件,否則(回傳 null)就包裝成 Proxy。

再看 Proxy:

private static class Proxy implements com.example.aidltest.IMyAidlInterface {
	private android.os.IBinder mRemote;

	Proxy(android.os.IBinder remote) {
		mRemote = remote;
	}

	@Override
	public android.os.IBinder asBinder() {
		return mRemote;
	}

	public java.lang.String getInterfaceDescriptor() {
		return DESCRIPTOR;
	}

	@Override
	public void basicTypes(int anInt, long aLong, boolean aBoolean,
			float aFloat, double aDouble, java.lang.String aString)
			throws android.os.RemoteException {
		android.os.Parcel _data = android.os.Parcel.obtain();
		android.os.Parcel _reply = android.os.Parcel.obtain();
		try {
			_data.writeInterfaceToken(DESCRIPTOR);
			_data.writeInt(anInt);
			_data.writeLong(aLong);
			_data.writeInt(((aBoolean) ? (1) : (0)));
			_data.writeFloat(aFloat);
			_data.writeDouble(aDouble);
			_data.writeString(aString);
			mRemote.transact(Stub.TRANSACTION_basicTypes, _data, _reply, 0);
			_reply.readException();
		} finally {
			_reply.recycle();
			_data.recycle();
		}
	}

	@Override
	public com.example.aidltest.HelloMsg sayHello()
			throws android.os.RemoteException {
		android.os.Parcel _data = android.os.Parcel.obtain();
		android.os.Parcel _reply = android.os.Parcel.obtain();
		com.example.aidltest.HelloMsg _result;
		try {
			_data.writeInterfaceToken(DESCRIPTOR);
			mRemote.transact(Stub.TRANSACTION_sayHello, _data, _reply, 0);
			_reply.readException();
			if ((0 != _reply.readInt())) {
				_result = com.example.aidltest.HelloMsg.CREATOR
						.createFromParcel(_reply);
			}
		}
		// ...
	}
}

裡面的 mRemote 就是伺服器端傳過來的 Binder 物件。呼叫 transact 之後,會對應到 Stub 中的 onTransact。這裡用的是典型的靜態代理模式:Proxy 就是遠端 Binder 的本地代理人,可以把它理解為用戶端的中間人。

歸納一下兩個角色的分工:

  • Stub:伺服器端的中間人。實作 AIDL 介面並繼承 Binder,具備把 Binder 物件還原成原生介面物件的能力。
  • Proxy:用戶端的中間人。只實作 AIDL 介面,負責把呼叫序列化後交給遠端。

四、實作伺服器端

public class RemoteService extends Service {

	@Nullable
	@Override
	public IBinder onBind(Intent intent) {
		return new IMyAidlInterface.Stub() {
			@Override
			public HelloMsg sayHello() throws RemoteException {
				return new HelloMsg("wuliqing", 28);
			}
		};
	}
}

五、用戶端呼叫

public class MainActivity extends AppCompatActivity {

	private IMyAidlInterface iMyAidlInterface = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	@Override
	protected void onStart() {
		super.onStart();
		Intent intent = new Intent(this, RemoteService.class);
		bindService(intent, serviceConnection, BIND_AUTO_CREATE);
	}

	@Override
	protected void onStop() {
		super.onStop();
		unbindService(serviceConnection);
	}

	private ServiceConnection serviceConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			iMyAidlInterface = null;
		}
	};

	public void onClickToSayHello(View view) {
		if (iMyAidlInterface != null) {
			try {
				HelloMsg helloMsg = iMyAidlInterface.sayHello();
				Toast.makeText(this, helloMsg.toString(),
						Toast.LENGTH_SHORT).show();
			} catch (RemoteException e) {
				e.printStackTrace();
				Toast.makeText(this, e.toString(),
						Toast.LENGTH_SHORT).show();
			}
		}
	}
}

在 onServiceConnected() 回呼中,我們用 IMyAidlInterface.Stub.asInterface(service) 取得介面參照;之後用戶端就能透過它向伺服器端發送請求。

六、讓它真的跨進程

替 RemoteService 加上 process 屬性,讓它跑在與預設進程不同的行程裡:

<service
	android:name="RemoteService"
	android:process=":remote"></service>

上圖可以看到用戶端與伺服器確實分別跑在兩個進程中。點擊按鈕後,就能成功取回結果。

最後用一張流程圖把整個呼叫鏈串起來:用戶端 Proxy 把參數寫進 Parcel 並呼叫 transact → 系統 Binder 執行緒池把請求轉給伺服器端 Stub.onTransact → 解包後呼叫真正的實作方法 → 結果再寫回 Parcel 沿原路返回。理解這條路徑,之後要擴充 AIDL 介面或排查 RemoteException 都會順手很多。

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