Messenger作為跨進(jìn)程,是很常用的方法,輕便,已經(jīng)基于AIDL做了很多的封裝了,但是這個(gè)方法只能傳輸比較小的數(shù)據(jù),如果要傳輸大一些的數(shù)據(jù)咋辦呢?可以使用Bundle.putBinder,我這里做個(gè)記錄:
首先創(chuàng)建一個(gè)aidl,GetLargeOne.aidl
// GetLargeOne.aidl
// Declare any non-default types here with import statements
//為了解決傳輸數(shù)據(jù)量很大的時(shí)候處理的情況
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)魉瓦^(guò)來(lái)的數(shù)據(jù)
}
注意,如果是跨進(jìn)程,必須使用的是GetLargeOne.Stub.asInterface來(lái)處理,否者會(huì)報(bào)錯(cuò)。
因?yàn)閍idl不支持泛型,所以需要什么類(lèi)型,你就給自己定義一個(gè)什么類(lèi)型就好了。以上代碼的重點(diǎn),其實(shí)就是GetLargeOne.Stub.asInterface,我也是試了一段時(shí)間,才幡然醒悟的,因?yàn)楹芏噘Y料,都是直接奔著使用aidl的方式去傳輸去了,如果是使用Messenger在這里做的綁定,其實(shí)也可以這樣寫(xiě)的。
以上的發(fā)送端,和接收端,并不局限于你在哪個(gè)進(jìn)程,只在于,你是誰(shuí)發(fā)送,誰(shuí)接收。
參考:https://developer.android.com/guide/components/aidl?hl=zh-cn#Implement