日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Android使用Intent傳遞組件大數據_Android

作者:??晚來天欲雪_?? ? 更新時間: 2022-09-01 編程語言

數據傳輸

在Android開發過程中,我們常常通過Intent在各個組件之間傳遞數據。例如在使用startActivity(android.content.Intent)方法啟動新的 Activity 時,我們就可以通過創建Intent對象然后調用putExtra()?方法傳輸參數。

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

啟動完新的Activity之后,我們可以在新的Activity獲取傳輸的數據。

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

一般情況下,我們傳遞的數據都是很小的數據,但是有時候我們想傳輸一個大對象,比如bitmap,就有可能出現問題。

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

當調用該方法啟動新的Activity的時候就會拋出異常。

android.os.TransactionTooLargeException: data parcel size 1048920 bytes

很明顯,出錯的原因是我們傳輸的數據量太大了。在官方文檔中有這樣的描述:

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。

即緩沖區最大1MB,并且這是該進程中所有正在進行中的傳輸對象所公用的。所以我們能傳輸的數據大小實際上應該比1M要小。

替代方案

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

由于我們要將數據存放在Binder里面,所以先創建一個類繼承自Binder。data就是我們傳遞的數據對象。

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)

然后正常啟動新界面,發現可以跳轉過去,而且新界面也可以接收到我們傳遞的數據。

為什么通過這種方式就可以繞過1M的緩沖區限制呢,這是因為直接通過Intent傳遞的時候,系統采用的是拷貝到緩沖區的方式,而通過putBinder的方式則是利用共享內存,而共享內存的限制遠遠大于1M,所以不會出現異常。

原文鏈接:https://juejin.cn/post/7109862936604049415

欄目分類
最近更新