Messenger
作爲跨進程,是很常用的方法,輕便,已經基於AIDL做了很多的封裝了,但是這個方法只能傳輸比較小的數據,如果要傳輸大一些的數據咋辦呢?可以使用Bundle.putBinder
,我這裏做個記錄:
首先創建一個aidl,GetLargeOne.aidl
// GetLargeOne.aidl
// Declare any non-default types here with import statements
//爲了解決傳輸數據量很大的時候處理的情況
interface GetLargeOne {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
String getOne();
}
在發送端的使用方式:
val data = Bundle()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
data.putBinder("one", object : GetLargeOne.Stub() {
override fun getOne(): String {
return "要傳送的數據"
}
})
}
在接收端的使用方式:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
val string = GetLargeOne.Stub.asInterface(data?.getBinder("one")).one
//string,就是上面傳送過來的數據
}
注意,如果是跨進程,必須使用的是GetLargeOne.Stub.asInterface
來處理,否者會報錯。
因爲aidl不支持泛型,所以需要什麼類型,你就給自己定義一個什麼類型就好了。以上代碼的重點,其實就是GetLargeOne.Stub.asInterface
,我也是試了一段時間,才幡然醒悟的,因爲很多資料,都是直接奔着使用aidl的方式去傳輸去了,如果是使用Messenger
在這裏做的綁定,其實也可以這樣寫的。
以上的發送端,和接收端,並不侷限於你在哪個進程,只在於,你是誰發送,誰接收。
參考:https://developer.android.com/guide/components/aidl?hl=zh-cn#Implement