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

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

Android?Intent傳遞大量數(shù)據(jù)出現(xiàn)問題解決_Android

作者:AnRFDev ? 更新時(shí)間: 2022-09-21 編程語(yǔ)言

正文

官方文檔?https://developer.android.google.cn/guide/components/activities/parcelables-and-bundles

在sendBroadcast,startActivity時(shí),我們會(huì)用到Intent。 Intent可以攜帶一些數(shù)據(jù),比如基本類型數(shù)據(jù)int、Boolean,或是String,或是序列化對(duì)象,Parcelable與Serializable。

異常TransactionTooLargeException

Intent傳遞數(shù)據(jù)時(shí),如果數(shù)據(jù)太大,可能會(huì)出現(xiàn)異常TransactionTooLargeException。

注意:

在 Android 7.0(API 級(jí)別 24)或更高版本中,系統(tǒng)會(huì)在運(yùn)行時(shí)拋出 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方法會(huì)報(bào)出RemoteException

public native boolean transactNative(int code, Parcel data, Parcel reply,
            int flags) throws RemoteException;

拋出異常與Binder有關(guān)。

通過 intent 發(fā)送數(shù)據(jù)時(shí),應(yīng)小心地將數(shù)據(jù)大小限制為幾 KB。發(fā)送過多數(shù)據(jù)會(huì)導(dǎo)致系統(tǒng)拋出?TransactionTooLargeException?異常。

Intent攜帶信息的大小受Binder限制

Intent攜帶信息的大小其實(shí)是受Binder限制。本文標(biāo)題也可以改為“Binder傳遞數(shù)據(jù)大小限制”。

數(shù)據(jù)以Parcel對(duì)象的形式存放在Binder傳遞緩存中。 如果數(shù)據(jù)或返回值比傳遞buffer大,則此次傳遞調(diào)用失敗并拋出TransactionTooLargeException異常。

Binder事務(wù)緩沖區(qū)有一個(gè)限定大小,通常是1Mb。由進(jìn)程中正在處理的所有事務(wù)共享緩存空間。

由于此限制是進(jìn)程級(jí)別而不是 Activity 級(jí)別的限制,因此這些事務(wù)包括應(yīng)用中的所有 binder 事務(wù),例如 onSaveInstanceStatestartActivity 以及與系統(tǒng)的任何互動(dòng)。超過大小限制時(shí),將引發(fā) TransactionTooLargeException。

對(duì)于 savedInstanceState 的具體情況,應(yīng)將數(shù)據(jù)量保持在較小的規(guī)模,因?yàn)橹灰脩艨梢苑祷氐皆?Activity,系統(tǒng)進(jìn)程就需要保留所提供的數(shù)據(jù)(即使 Activity 的進(jìn)程已終止)。我們建議您將保存的狀態(tài)保持在 50k 數(shù)據(jù)以下。

為什么Binder要限制傳輸數(shù)據(jù)的大小

個(gè)人推測(cè),作為一種IPC的方式,Binder并不是為傳輸大量數(shù)據(jù)而設(shè)計(jì)。

替代方案

當(dāng)需要傳遞長(zhǎng)字符串、Bitmap等時(shí),不要考慮使用Intent傳遞數(shù)據(jù)的方案

1、單例

2、EventBus

3、Application

4、持久化數(shù)據(jù)

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

欄目分類
最近更新