Android使用Intent傳遞組件大數(shù)據(jù)
數(shù)據(jù)傳輸
在Android開發(fā)過程中,我們常常通過Intent在各個組件之間傳遞數(shù)據(jù)。例如在使用startActivity(android.content.Intent)方法啟動新的 Activity 時,我們就可以通過創(chuàng)建Intent對象然后調(diào)用putExtra() 方法傳輸參數(shù)。
val intent = Intent(this, TestActivity::class.java)
intent.putExtra("name","name")
startActivity(intent)啟動完新的Activity之后,我們可以在新的Activity獲取傳輸?shù)臄?shù)據(jù)。
val name = getIntent().getStringExtra("name")一般情況下,我們傳遞的數(shù)據(jù)都是很小的數(shù)據(jù),但是有時候我們想傳輸一個大對象,比如bitmap,就有可能出現(xiàn)問題。
val intent = Intent(this, TestActivity::class.java)
val data= ByteArray( 1024 * 1024)
intent.putExtra("param",data)
startActivity(intent)當調(diào)用該方法啟動新的Activity的時候就會拋出異常。
android.os.TransactionTooLargeException: data parcel size 1048920 bytes
很明顯,出錯的原因是我們傳輸?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,并且這是該進程中所有正在進行中的傳輸對象所公用的。所以我們能傳輸?shù)臄?shù)據(jù)大小實際上應(yīng)該比1M要小。
替代方案
- 我們可以通過靜態(tài)變量來共享數(shù)據(jù)
- 使用
bundle.putBinder()方法完成大數(shù)據(jù)傳遞。
由于我們要將數(shù)據(jù)存放在Binder里面,所以先創(chuàng)建一個類繼承自Binder。data就是我們傳遞的數(shù)據(jù)對象。
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)然后正常啟動新界面,發(fā)現(xiàn)可以跳轉(zhuǎn)過去,而且新界面也可以接收到我們傳遞的數(shù)據(jù)。
為什么通過這種方式就可以繞過1M的緩沖區(qū)限制呢,這是因為直接通過Intent傳遞的時候,系統(tǒng)采用的是拷貝到緩沖區(qū)的方式,而通過putBinder的方式則是利用共享內(nèi)存,而共享內(nèi)存的限制遠遠大于1M,所以不會出現(xiàn)異常。
到此這篇關(guān)于Android使用Intent傳遞組件大數(shù)據(jù)的文章就介紹到這了,更多相關(guān)Android Intent 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Android中backgroundDimEnabled的作用
這篇文章主要介紹了Android中backgroundDimEnabled的作用的相關(guān)資料,希望通過本文能幫助到大家,讓大家理解掌握這部分內(nèi)容,需要的朋友可以參考下2017-10-10
Android 關(guān)于ExpandableListView刷新問題的解決方法
下面小編就為大家?guī)硪黄狝ndroid 關(guān)于ExpandableListView刷新問題的解決方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-12-12
Andoroid實現(xiàn)底部圖片選擇Dialog效果
這篇文章主要介紹了Andoroid實現(xiàn)底部圖片選擇Dialog效果,需要的朋友可以參考下2017-10-10
Android編程實現(xiàn)系統(tǒng)重啟與關(guān)機的方法
這篇文章主要介紹了Android編程實現(xiàn)系統(tǒng)重啟與關(guān)機的方法,較為詳細的分析了Android運行原理與源碼剖析,講述了Android編程實現(xiàn)系統(tǒng)重啟與關(guān)機的相關(guān)技巧與注意事項,需要的朋友可以參考下2016-02-02

