Android Intent傳遞大量數(shù)據(jù)出現(xiàn)問題解決
正文
官方文檔 https://developer.android.google.cn/guide/components/activities/parcelables-and-bundles
在sendBroadcast,startActivity時,我們會用到Intent。 Intent可以攜帶一些數(shù)據(jù),比如基本類型數(shù)據(jù)int、Boolean,或是String,或是序列化對象,Parcelable與Serializable。
異常TransactionTooLargeException
Intent傳遞數(shù)據(jù)時,如果數(shù)據(jù)太大,可能會出現(xiàn)異常TransactionTooLargeException。
注意:
在 Android 7.0(API 級別 24)或更高版本中,系統(tǒng)會在運行時拋出 TransactionTooLargeException 異常。在較低版本的 Android 中,系統(tǒng)僅在 logcat 中顯示警告。
TransactionTooLargeException繼承了RemoteException
package android.os;
public class TransactionTooLargeException extends RemoteException {
public TransactionTooLargeException() {
super();
}
public TransactionTooLargeException(String msg) {
super(msg);
}
}
追蹤到Binder,它的transactNative方法會報出RemoteException
public native boolean transactNative(int code, Parcel data, Parcel reply,
int flags) throws RemoteException;
拋出異常與Binder有關。
通過 intent 發(fā)送數(shù)據(jù)時,應小心地將數(shù)據(jù)大小限制為幾 KB。發(fā)送過多數(shù)據(jù)會導致系統(tǒng)拋出 TransactionTooLargeException 異常。
Intent攜帶信息的大小受Binder限制
Intent攜帶信息的大小其實是受Binder限制。本文標題也可以改為“Binder傳遞數(shù)據(jù)大小限制”。
數(shù)據(jù)以Parcel對象的形式存放在Binder傳遞緩存中。 如果數(shù)據(jù)或返回值比傳遞buffer大,則此次傳遞調(diào)用失敗并拋出TransactionTooLargeException異常。
Binder事務緩沖區(qū)有一個限定大小,通常是1Mb。由進程中正在處理的所有事務共享緩存空間。
由于此限制是進程級別而不是 Activity 級別的限制,因此這些事務包括應用中的所有 binder 事務,例如 onSaveInstanceState,startActivity 以及與系統(tǒng)的任何互動。超過大小限制時,將引發(fā) TransactionTooLargeException。
對于 savedInstanceState 的具體情況,應將數(shù)據(jù)量保持在較小的規(guī)模,因為只要用戶可以返回到該 Activity,系統(tǒng)進程就需要保留所提供的數(shù)據(jù)(即使 Activity 的進程已終止)。我們建議您將保存的狀態(tài)保持在 50k 數(shù)據(jù)以下。
為什么Binder要限制傳輸數(shù)據(jù)的大小
個人推測,作為一種IPC的方式,Binder并不是為傳輸大量數(shù)據(jù)而設計。
替代方案
當需要傳遞長字符串、Bitmap等時,不要考慮使用Intent傳遞數(shù)據(jù)的方案
1、單例
2、EventBus
3、Application
4、持久化數(shù)據(jù)
以上就是Android Intent傳遞大量數(shù)據(jù)出現(xiàn)問題解決的詳細內(nèi)容,更多關于Android Intent傳遞大量數(shù)據(jù)的資料請關注腳本之家其它相關文章!
相關文章
使用Android studio查看Kotlin的字節(jié)碼教程
這篇文章主要介紹了使用Android studio查看Kotlin的字節(jié)碼教程,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
Android TabLayout(選項卡布局)簡單用法實例分析
這篇文章主要介紹了Android TabLayout(選項卡布局)簡單用法,結合實例形式簡單分析了Android選項卡布局的界面布局與功能實現(xiàn)具體相關技巧,需要的朋友可以參考下2016-01-01
Android利用ViewDragHelper輕松實現(xiàn)拼圖游戲的示例
本篇文章主要介紹了Android利用ViewDragHelper輕松實現(xiàn)拼圖游戲的示例,非常具有實用價值,需要的朋友可以參考下2017-11-11
Android webview加載https鏈接錯誤或無響應的解決
這篇文章主要介紹了Android webview加載https鏈接錯誤或無響應的解決,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
android中SharedPreferences實現(xiàn)存儲用戶名功能
本篇文章主要介紹了android中SharedPreferences實現(xiàn)保存用戶名功能,詳細的介紹了SharedPreferences的功能,需要的朋友可以參考下2017-04-04

