Messenger
作為跨進(jìn)程,是很常用的方法,輕便脚线,已經(jīng)基于AIDL做了很多的封裝了,但是這個方法只能傳輸比較小的數(shù)據(jù)弥搞,如果要傳輸大一些的數(shù)據(jù)咋辦呢邮绿?可以使用Bundle.putBinder
渠旁,我這里做個記錄:
首先創(chuàng)建一個aidl,GetLargeOne.aidl
// GetLargeOne.aidl
// Declare any non-default types here with import statements
//為了解決傳輸數(shù)據(jù)量很大的時候處理的情況
interface GetLargeOne {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
String getOne();
}
在發(fā)送端的使用方式:
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 "要傳送的數(shù)據(jù)"
}
})
}
在接收端的使用方式:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
val string = GetLargeOne.Stub.asInterface(data?.getBinder("one")).one
//string船逮,就是上面?zhèn)魉瓦^來的數(shù)據(jù)
}
注意顾腊,如果是跨進(jìn)程,必須使用的是GetLargeOne.Stub.asInterface
來處理挖胃,否者會報錯杂靶。
因為aidl不支持泛型,所以需要什么類型酱鸭,你就給自己定義一個什么類型就好了吗垮。以上代碼的重點,其實就是GetLargeOne.Stub.asInterface
凹髓,我也是試了一段時間烁登,才幡然醒悟的,因為很多資料蔚舀,都是直接奔著使用aidl的方式去傳輸去了饵沧,如果是使用Messenger
在這里做的綁定,其實也可以這樣寫的赌躺。
以上的發(fā)送端狼牺,和接收端,并不局限于你在哪個進(jìn)程礼患,只在于是钥,你是誰發(fā)送,誰接收讶泰。
參考:https://developer.android.com/guide/components/aidl?hl=zh-cn#Implement