欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android使用Intent傳遞組件大數(shù)據(jù)

 更新時(shí)間:2022年07月08日 10:28:15   作者:? 晚來天欲雪_??  
這篇文章主要介紹了Android使用Intent傳遞組件大數(shù)據(jù),文章圍繞主題展開詳細(xì)的內(nèi)容詳情,感興趣的朋友可以參考一下

數(shù)據(jù)傳輸

在Android開發(fā)過程中,我們常常通過Intent在各個(gè)組件之間傳遞數(shù)據(jù)。例如在使用startActivity(android.content.Intent)方法啟動(dòng)新的 Activity 時(shí),我們就可以通過創(chuàng)建Intent對(duì)象然后調(diào)用putExtra() 方法傳輸參數(shù)。

val intent = Intent(this, TestActivity::class.java)
intent.putExtra("name","name")
startActivity(intent)

啟動(dòng)完新的Activity之后,我們可以在新的Activity獲取傳輸?shù)臄?shù)據(jù)。

val name = getIntent().getStringExtra("name")

一般情況下,我們傳遞的數(shù)據(jù)都是很小的數(shù)據(jù),但是有時(shí)候我們想傳輸一個(gè)大對(duì)象,比如bitmap,就有可能出現(xiàn)問題。

val intent = Intent(this, TestActivity::class.java)
val data= ByteArray( 1024 * 1024)
intent.putExtra("param",data)
startActivity(intent)

當(dāng)調(diào)用該方法啟動(dòng)新的Activity的時(shí)候就會(huì)拋出異常。

android.os.TransactionTooLargeException: data parcel size 1048920 bytes

很明顯,出錯(cuò)的原因是我們傳輸?shù)臄?shù)據(jù)量太大了。在官方文檔中有這樣的描述:

The Binder transaction buffer has a limited fixed size, currently 1Mb, which is shared by all transactions in progress for the process. Consequently this exception can be thrown when there are many transactions in progress even when most of the individual transactions are of moderate size。

即緩沖區(qū)最大1MB,并且這是該進(jìn)程中所有正在進(jìn)行中的傳輸對(duì)象所公用的。所以我們能傳輸?shù)臄?shù)據(jù)大小實(shí)際上應(yīng)該比1M要小。

替代方案

  • 我們可以通過靜態(tài)變量來共享數(shù)據(jù)
  • 使用bundle.putBinder()方法完成大數(shù)據(jù)傳遞。

由于我們要將數(shù)據(jù)存放在Binder里面,所以先創(chuàng)建一個(gè)類繼承自Binder。data就是我們傳遞的數(shù)據(jù)對(duì)象。

class BigBinder(val data:ByteArray):Binder()

然后傳遞

val intent = Intent(this, TestActivity::class.java)
val data= ByteArray( 1024 * 1024)
val bundle = Bundle()
val bigData = BigBinder(data)
bundle.putBinder("bigData",bigData)
intent.putExtra("bundle",bundle)
startActivity(intent)

然后正常啟動(dòng)新界面,發(fā)現(xiàn)可以跳轉(zhuǎn)過去,而且新界面也可以接收到我們傳遞的數(shù)據(jù)。

為什么通過這種方式就可以繞過1M的緩沖區(qū)限制呢,這是因?yàn)橹苯油ㄟ^Intent傳遞的時(shí)候,系統(tǒng)采用的是拷貝到緩沖區(qū)的方式,而通過putBinder的方式則是利用共享內(nèi)存,而共享內(nèi)存的限制遠(yuǎn)遠(yuǎn)大于1M,所以不會(huì)出現(xiàn)異常。

到此這篇關(guān)于Android使用Intent傳遞組件大數(shù)據(jù)的文章就介紹到這了,更多相關(guān)Android Intent 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論