網站首頁 編程語言 正文
數據傳輸
在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
相關推薦
- 2022-03-19 淺談Go1.18中的泛型編程_Golang
- 2024-04-04 linux設置串口波特率和讀取
- 2022-10-27 使用python+pandas讀寫xlsx格式中的數據_python
- 2024-04-06 @Delete通過批量刪除的方法
- 2022-11-05 LyScript實現計算片段Hash并寫出Excel的示例代碼_python
- 2022-08-29 Python?GUI?圖形用戶界面_python
- 2022-12-10 OpenMP深入剖析reduction子句教程_C 語言
- 2022-05-17 Git分支管理策略_其它綜合
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支