如何处理TransactionTooLargeException

问题描述 投票:213回答:36

我有一个TransactionTooLargeException。不可重复。在文档中说

Binder事务失败,因为它太大了。

在远程过程调用期间,调用的参数和返回值将作为存储在Binder事务缓冲区中的Parcel对象传输。如果参数或返回值太大而不适合事务缓冲区,则调用将失败并抛出TransactionTooLargeException。

...

当远程过程调用抛出TransactionTooLargeException时,有两种可能的结果。客户端无法将其请求发送到服务(很可能,如果参数太大而无法放入事务缓冲区中),或者服务无法将其响应发送回客户端(最有可能的话,如果返回值为太大而不适合事务缓冲区)。

...

所以在某个地方,我正在传递或接收超出某个未知限度的论据。哪里?

堆栈跟踪没有显示任何有用的内容:

java.lang.RuntimeException: Adding window failed
at android.view.ViewRootImpl.setView(ViewRootImpl.java:548)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:406)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:320)
at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:152)
at android.view.Window$LocalWindowManager.addView(Window.java:557)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2897)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$600(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1262)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:4977)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.TransactionTooLargeException
at android.os.BinderProxy.transact(Native Method)
at android.view.IWindowSession$Stub$Proxy.add(IWindowSession.java:569)
at android.view.ViewRootImpl.setView(ViewRootImpl.java:538)
... 16 more
android.os.TransactionTooLargeException
at android.os.BinderProxy.transact(Native Method)
at android.view.IWindowSession$Stub$Proxy.add(IWindowSession.java:569)
at android.view.ViewRootImpl.setView(ViewRootImpl.java:538)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:406)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:320)
at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:152)
at android.view.Window$LocalWindowManager.addView(Window.java:557)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2897)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$600(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1262)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:4977)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)

它似乎与观点有关?这与远程过程调用有什么关系?

也许重要:Android版本:4.0.3,设备:HTC One X.

android exception
36个回答
144
投票

我遇到了这个问题,我发现当服务和应用程序之间交换大量数据时(这涉及传输大量缩略图)。实际上数据大小约为500kb,IPC事务缓冲区大小设置为1024KB。我不确定为什么它超出了事务缓冲区。

当您通过intent extras传递大量数据时,也会发生这种情况

当您在应用程序中遇到此异常时,请分析您的代码。

  1. 您是在服务和应用程序之间交换大量数据吗?
  2. 使用意图来共享大量数据(例如,用户从图库共享新闻共享中选择大量文件,将使用意图传输所选文件的URI)
  3. 从服务接收位图文件
  4. 等待android用大量数据回复(例如,当用户安装了大量应用程序时,getInstalledApplications())
  5. 使用applyBatch(),其中有许多操作待定

当你得到这个例外时如何处理

如果可能,将大操作拆分为小块,例如,而不是使用1000次操作调用applyBatch(),每次调用100。

不要在服务和应用程序之间交换大量数据(> 1MB)

我不知道该怎么做,但是,不要查询android,它可以返回大量数据:-)


8
投票

我也在三星S3上遇到这个例外。我怀疑有2个根本原因,

  1. 你有加载和占用太多内存的位图,使用缩小尺寸
  2. 你在drawable-_dpi文件夹中缺少一些drawables,android在drawable中查找它们,并调整它们的大小,使你的setContentView突然跳转并使用大量内存。

使用DDMS并在播放应用程序时查看堆,这将为您提供有关setcontentview创建问题的一些指示。

我复制了所有文件夹中的所有drawables以摆脱问题2。

问题已解决。


4
投票

所以对我们来说,我们试图通过AIDL接口将太大的对象发送到远程服务。交易规模不能超过1MB。请求被分解为512KB的单独块,并通过接口一次发送一个。一个残酷的解决方案,我知道,但嘿 - 它的Android :(


3
投票

最近我在使用Android的Contacts Provider时遇到了一个有趣的案例。

我需要从内部联系人数据库加载联系人的照片,并根据系统架构,所有这些数据都通过查询提供给Contacts Provider。

由于它作为一个单独的应用程序工作 - 所有类型的数据传输都是通过使用Binder机制执行的,因此Binder缓冲区在这里发挥作用。

我的主要错误是我没有关闭来自Contacts Provider的blob数据的Cursor,因此为提供者分配的内存增加了,这使Binder缓冲区膨胀,直到我的LogCat输出中有大量的!!!FAILED BINDER TRANSACTION!!!消息。

因此,主要的想法是,当您与外部内容提供商合作并从中获取Cursors时,请在完成与他们合作时关闭它。


2
投票

在我的情况下,在本机库与SIGSEGV崩溃后,我将TransactionTooLargeException作为二级崩溃。未报告本机库崩溃,因此我只收到TransactionTooLargeException。


2
投票

在尝试批量插入大型ContentValues []时,我在syncadapter中得到了这个。我决定修复它如下:

try {
    count = provider.bulkInsert(uri, contentValueses);
} catch (TransactionTooLarge e) {
    int half = contentValueses.length/2;
    count += provider.bulkInsert(uri, Arrays.copyOfRange(contentValueses, 0, half));
    count += provider.bulkInsert(uri, Arrays.copyOfRange(contentValueses, half, contentValueses.length));
}

2
投票

您已从onSaveInstanceState方法清除旧的InstanceState,它将运行良好。我正在为我的viewpager使用FragmentStatePagerAdapter,所以我将Override方法保留在我的父活动中,以便清除InstanceState。

@Override
protected void onSaveInstanceState(Bundle InstanceState) {
             super.onSaveInstanceState(InstanceState);
             InstanceState.clear();
}

我从这里找到了这个解决方案android.os.TransactionTooLargeException on Nougat


2
投票

对我来说它也是FragmentStatePagerAdapter,但是压倒性的saveState()不起作用。以下是我修复它的方法:

在调用FragmentStatePagerAdapter构造函数时,在类中保留一个单独的片段列表,并添加一个方法来删除片段:

class PagerAdapter extends FragmentStatePagerAdapter {
    ArrayList<Fragment> items;

    PagerAdapter(ArrayList<Fragment> frags) {
        super(getFragmentManager()); //or getChildFragmentManager() or getSupportFragmentManager()
        this.items = new ArrayList<>();
        this.items.addAll(frags);
    }

    public void removeFragments() {
        Iterator<Fragment> iter = items.iterator();

        while (iter.hasNext()) {
            Fragment item = iter.next();
                getFragmentManager().beginTransaction().remove(item).commit();
                iter.remove();
            }
            notifyDataSetChanged();
        }
    }
    //...getItem() and etc methods...
}

然后在Activity中,保存ViewPager位置并在重写的adapter.removeFragments()方法中调用onSaveInstanceState()

private int pagerPosition;

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    //save other view state here
    pagerPosition = mViewPager.getCurrentItem();
    adapter.removeFragments();
}

最后,在重写的onResume()方法中,如果它不是null,则重新实例化适配器。 (如果它是null,那么Activity第一次被打开,或者在应用程序被Android杀掉之后,其中onCreate将创建适配器。)

@Override
public void onResume() {
    super.onResume();
    if (adapter != null) {
        adapter = new PagerAdapter(frags);
        mViewPager.setAdapter(adapter);
        mViewPager.setCurrentItem(currentTabPosition);
    }
}

1
投票

确保不要放入大尺寸的Intent对象数据。在我的情况下,我添加了字符串500k大小,然后开始另一个活动。它始终因此异常而失败。我避免使用活动的静态变量在活动之间共享数据 - 您不必将它们发送到Intent然后从中拉出来。

我有什么:

String html = new String();//some string of 500K data.
Intent intent = new Intent(MainActivity.this, PageWebView.class);
//this is workaround - I just set static variable and then access it from another    activity.
MainActivity.htmlBody = timelineDb.getHTMLBodyForTweet(tweet);
//This line was present and it actually failed with the same exception you had.
//intent.putExtra("com.gladimdim.offtie.webview", html);

1
投票

我找到了这个的根本原因(我们得到了“添加窗口失败”和文件描述符泄漏,如mvds所说)。

在Android 4.4的bug中有一个BitmapFactory.decodeFileDescriptor()。它只发生在inPurgeableinInputShareableBitmapOptions被设置为true时。这导致许多地方的许多问题与文件交互。

请注意,该方法也是从MediaStore.Images.Thumbnails.getThumbnail()调用的。

Universal Image Loader受此问题的影响。毕加索和格莱德似乎没有受到影响。 https://github.com/nostra13/Android-Universal-Image-Loader/issues/1020


1
投票

writeToParcel(Parcel dest,int flags)方法中的这一行代码帮助我摆脱了TransactionTooLargeException。

dest=Parcel.obtain(); 

在此代码之后,我只将所有数据写入parcel对象,即dest.writeInt()等。


39
投票

这不是一个明确的答案,但它可能会揭示TransactionTooLargeException的原因,并帮助查明问题。

虽然大多数答案都涉及大量传输的数据,但我看到在重度滚动和缩放以及重复打开ActionBar微调器菜单后偶然抛出此异常。点击操作栏时会发生崩溃。 (这是一个自定义地图应用程序)

传递的唯一数据似乎是从“输入调度程序”到应用程序的触摸。我认为在“事务缓冲区”中这不可能合理地接近1 mb。

我的应用程序运行在四核1.6 GHz设备上,并使用3个线程进行重载,为UI线程保留一个核心。此外,该应用程序使用android:largeHeap,剩下10 MB未使用的堆,并留下100 MB的空间来增加堆。所以我不会说这是一个资源问题。

崩溃总是紧接着这些行:

W/InputDispatcher( 2271): channel ~ Consumer closed input channel or an error occurred.  events=0x9
E/InputDispatcher( 2271): channel ~ Channel is unrecoverably broken and will be disposed!
E/JavaBinder(28182): !!! FAILED BINDER TRANSACTION !!!

这些不一定按照那个顺序打印,但是(据我检查)在同一毫秒内发生。

为清楚起见,堆栈跟踪本身与问题中的相同:

E/AndroidRuntime(28182): java.lang.RuntimeException: Adding window failed
..
E/AndroidRuntime(28182): Caused by: android.os.TransactionTooLargeException

深入研究android的源代码,找到以下几行:

框架/碱/核心/ JNI / android_util_Binder.cpp:

case FAILED_TRANSACTION:
    ALOGE("!!! FAILED BINDER TRANSACTION !!!");
    // TransactionTooLargeException is a checked exception, only throw from certain methods.
    // FIXME: Transaction too large is the most common reason for FAILED_TRANSACTION
    //        but it is not the only one.  The Binder driver can return BR_FAILED_REPLY
    //        for other reasons also, such as if the transaction is malformed or
    //        refers to an FD that has been closed.  We should change the driver
    //        to enable us to distinguish these cases in the future.
    jniThrowException(env, canThrowRemoteException
            ? "android/os/TransactionTooLargeException"
                    : "java/lang/RuntimeException", NULL);

对我而言,听起来我可能正在使用这个未记录的功能,其中交易因其他原因而失败,而不是交易是TooLarge。他们应该把它命名为TransactionTooLargeOrAnotherReasonException

这时我没有解决问题,但如果我发现有用的东西,我会更新这个答案。

更新:事实证明我的代码泄漏了一些文件描述符,其数量在linux中最大化(通常为1024),这似乎触发了异常。毕竟这是一个资源问题。我通过打开/dev/zero 1024次验证了这一点,这导致了UI相关操作中的各种奇怪的异常,包括上面的例外,甚至一些SIGSEGV。显然无法打开文件/套接字并不是在Android中非常干净地处理/报告的内容。


1
投票

当我尝试通过Intent发送位图时,我遇到了同样的问题,同时当它发生时,我折叠了应用程序。

本文中描述的enter link description here是如何在Activity停止的过程中发生的,这意味着Activity正在尝试将其保存的状态Bundle发送到系统操作系统,以便以后安全保存(在配置更改或进程死亡后) )但它发送的一个或多个Bundle太大了。

我通过在我的Activity中重写onSaveInstanceState来解决它:

@Override
protected void onSaveInstanceState(Bundle outState) {
    // super.onSaveInstanceState(outState);
}

并评论称超级。这是一个肮脏的黑客,但它工作得很好。位图已成功发送而没有崩溃。希望这会对某人有所帮助。


1
投票

我从Android Espresso测试中的Stackoverflow错误中得到了TransactionTooLargeException。当我为我的应用程序取消Logcat过滤器时,我在日志中找到了stackoverflow错误堆栈跟踪。

我猜测Espresso在尝试处理非常大的异常堆栈跟踪时导致了TransactionTooLargeException。


1
投票

可以使用:

android:largeHeap="true"

在应用程序标记下的Android Manifest中。

这解决了我的问题!


1
投票

我也面临这个问题,因为Bitmap数据从一个活动传递到另一个活动,但我通过将我的数据作为静态数据来解决这个问题,这对我来说非常有用

在活动中:

public static Bitmap bitmap_image;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_first);
   bitmap_image=mybitmap;
}

在第二项活动中:

 @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);
   Bitmap mybitmap=first.bitmap_image;
}

0
投票

一个解决方案是让app将ArrayList(或导致问题的任何对象)写入文件系统,然后通过Intent将对该文件的引用(例如,filename / path)传递给IntentService,然后让IntentService检索文件内容并将其转换回ArrayList。

当IntentService完成该文件时,它应该删除它或通过本地广播将指令传递回应用程序以删除它创建的文件(传回提供给它的相同文件引用)。

有关更多信息,请参阅my answer to this related problem


0
投票

作为Intent,内容提供商,Messenger,所有系统服务,如电话,振动器等,都使用Binder的IPC基础设施提供商。此外,活动生命周期回调也使用此基础设施。

1MB是特定时刻系统中执行的所有活页夹事务的总限制。

如果发送意图时发生了大量事务,即使额外数据不大,也可能会失败。 http://codetheory.in/an-overview-of-android-binder-framework/


0
投票

当我在我的应用程序中处理WebView时,它会发生。我认为这与addView和UI资源有关。在我的应用程序中,我在WebViewActivity中添加了一些代码,如下所示它运行正常:

@Override
protected void onDestroy() {
    if (mWebView != null) {
        ((ViewGroup) mWebView.getParent()).removeView(mWebView);  
        mWebView.removeAllViews();  
        mWebView.destroy();
    }
    super.onDestroy();
}

0
投票

有太多可以发生TransactionTooLargeException的地方 - 这里是Android 8的新功能 - 如果内容太大,有人只是开始输入EditText时会崩溃。

它与AutoFillManager(API 26中的新增内容)和following中的StartSessionLocked()代码有关:

    mSessionId = mService.startSession(mContext.getActivityToken(),
            mServiceClient.asBinder(), id, bounds, value, mContext.getUserId(),
            mCallback != null, flags, mContext.getOpPackageName());

如果我理解正确,这会调用自动填充服务 - 在绑定器中传递AutofillManagerClient。当EditText有很多内容时,它似乎会导致TTLE。

一些事情可能会缓解它(或者无论如何我都在测试):在EditText的xml布局声明中添加android:importantForAutofill="noExcludeDescendants"。或者在代码中:

EditText et = myView.findViewById(R.id.scriptEditTextView);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    et.setImportantForAutofill(View.IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS);
}

第二个可怕的,可怕的解决方法也可能是覆盖performClick()onWindowFocusChanged()方法来捕获TextEdit子类本身的错误。但我认为这不是明智的......


0
投票

对我来说,当我试图通过意图将大位图图像从一个活动发送到另一个活动时发生了TransactionTooLargeException。我用Application's Global Variables解决了这个问题。

例如,如果要将大型位图图像从活动A发送到活动B,则将该位图图像存储在全局变量中

((Global) this.getApplication()).setBitmap(bitmap);

然后启动活动B并从全局变量读取

Bitmap bitmap = ((Global) this.getApplication()).getBitmap();

0
投票

在将(发送广播)位图对象传送到广播接收器时,我遇到了同样的问题。

intent.putExtra("image", bitmapImage); 

所以不要将它们作为位图发送。我将位图转换为字节数组。令我惊讶的是它有效!!!我想知道为什么Android不允许使用Bitmap传输大量数据但允许相同的通过字节数组。

 intent.putExtra("imageInByteArray", convertBitmapToByteArray(bitmapImage)); 

在接收器上我将字节数组转换回位图,这解决了我的问题。


30
投票

TransactionTooLargeException现在困扰我们大约4个月了,我们终于解决了这个问题!

发生的事情是我们在FragmentStatePagerAdapter中使用ViewPager。用户可以翻阅并创建100多个片段(它是一个阅读应用程序)。

虽然我们在destroyItem()中正确管理了这些片段,但在androroids实现FragmentStatePagerAdapter时有一个bug,它保留了对以下列表的引用:

private ArrayList<Fragment.SavedState> mSavedState = new ArrayList<Fragment.SavedState>();

当Android的FragmentStatePagerAdapter试图保存状态时,它会调用该函数

@Override
public Parcelable saveState() {
    Bundle state = null;
    if (mSavedState.size() > 0) {
        state = new Bundle();
        Fragment.SavedState[] fss = new Fragment.SavedState[mSavedState.size()];
        mSavedState.toArray(fss);
        state.putParcelableArray("states", fss);
    }
    for (int i=0; i<mFragments.size(); i++) {
        Fragment f = mFragments.get(i);
        if (f != null && f.isAdded()) {
            if (state == null) {
                state = new Bundle();
            }
            String key = "f" + i;
            mFragmentManager.putFragment(state, key, f);
        }
    }
    return state;
}

如您所见,即使您正确管理FragmentStatePagerAdapter子类中的片段,基类仍将为创建的每个片段存储Fragment.SavedState。当该阵列被转储到TransactionTooLargeException并且操作系统不喜欢100多个项目时,会发生parcelableArray

因此,我们的修复是覆盖saveState()方法,而不是为"states"存储任何东西。

@Override
public Parcelable saveState() {
    Bundle bundle = (Bundle) super.saveState();
    bundle.putParcelableArray("states", null); // Never maintain any states from the base class, just null it out
    return bundle;
}

0
投票

尝试使用EventBusContentProvider之类的解决方案。

如果你在同一个过程中(通常你的所有活动都是),尝试使用EventBus,因为在进程中数据交换不需要有点缓冲,所以你不必担心你的数据太大。 (你可以使用方法调用确实传递数据,而EventBus隐藏了丑陋的东西)以下是详细信息:

// one side
startActivity(intentNotTooLarge);
EventBus.getDefault().post(new FooEvent(theHugeData));

// the other side
@Subscribe public void handleData(FooEvent event) { /* get and handle data */ }

如果Intent的双方不在同一个过程中,请尝试一下ContentProvider


TransactionTooLargeException

Binder事务失败,因为它太大了。

在远程过程调用期间,调用的参数和返回值将作为存储在Binder事务缓冲区中的Parcel对象传输。如果参数或返回值太大而不适合事务缓冲区,则调用将失败并抛出TransactionTooLargeException。


30
投票

如果您需要调查导致崩溃的Parcel,您应该考虑尝试使用TooLargeTool

(我发现这是@Max Spencer根据接受的答案发表的评论,这对我的情况很有帮助。)


19
投票

对于那些因为查找TransactionTooLargeException异常的答案而感到极度失望的人,请尝试检查在实例状态中保存的内容。

在compile / targetSdkVersion <= 23上,我们只有关于大型保存状态的内部警告,但没有任何内容崩溃:

E/ActivityThread: App sent too much data in instance state, so it was ignored
    android.os.TransactionTooLargeException: data parcel size 713856 bytes
    at android.os.BinderProxy.transactNative(Native Method)
    at android.os.BinderProxy.transact(Binder.java:615)
    at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3604)
    at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3729)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6044)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

但是在compile / targetSdkVersion> = 24上,我们在这种情况下遇到了真正的RuntimeException崩溃:

java.lang.RuntimeException: android.os.TransactionTooLargeException: data parcel size 713860 bytes
    at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3737)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6044)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
 Caused by: android.os.TransactionTooLargeException: data parcel size 713860 bytes
   at android.os.BinderProxy.transactNative(Native Method)
   at android.os.BinderProxy.transact(Binder.java:615)
   at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3604)
   at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3729)
   at android.os.Handler.handleCallback(Handler.java:751) 
   at android.os.Handler.dispatchMessage(Handler.java:95) 
   at android.os.Looper.loop(Looper.java:154) 
   at android.app.ActivityThread.main(ActivityThread.java:6044) 
   at java.lang.reflect.Method.invoke(Native Method) 
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 

该怎么办?

将数据保存在本地数据库中,并仅将id保存在实例状态,您可以使用该状态来检索此数据。


11
投票

将应用程序发送到后台时,通常会抛出此异常。

所以我决定使用数据片段方法来完全规避onSavedInstanceStae生命周期。我的解决方案还处理复杂的实例状态并尽快释放内存。

首先,我创建了一个简单的片段来存储数据:

package info.peakapps.peaksdk.logic;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;

/**
 * A neat trick to avoid TransactionTooLargeException while saving our instance state
 */

public class SavedInstanceFragment extends Fragment {

    private static final String TAG = "SavedInstanceFragment";
    private Bundle mInstanceBundle = null;

    public SavedInstanceFragment() { // This will only be called once be cause of setRetainInstance()
        super();
        setRetainInstance( true );
    }

    public SavedInstanceFragment pushData( Bundle instanceState )
    {
        if ( this.mInstanceBundle == null ) {
            this.mInstanceBundle = instanceState;
        }
        else
        {
            this.mInstanceBundle.putAll( instanceState );
        }
        return this;
    }

    public Bundle popData()
    {
        Bundle out = this.mInstanceBundle;
        this.mInstanceBundle = null;
        return out;
    }

    public static final SavedInstanceFragment getInstance(FragmentManager fragmentManager )
    {
        SavedInstanceFragment out = (SavedInstanceFragment) fragmentManager.findFragmentByTag( TAG );

        if ( out == null )
        {
            out = new SavedInstanceFragment();
            fragmentManager.beginTransaction().add( out, TAG ).commit();
        }
        return out;
    }
}

然后在我的主要Activity上完全绕过保存的实例循环,并将respoinsibilty推迟到我的数据Fragment。无需在Fragments本身上使用它,sice将其状态自动添加到Activity的状态中:

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    SavedInstanceFragment.getInstance( getFragmentManager() ).pushData( (Bundle) outState.clone() );
    outState.clear(); // We don't want a TransactionTooLargeException, so we handle things via the SavedInstanceFragment
}

剩下的就是弹出保存的实例:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(SavedInstanceFragment.getInstance(getFragmentManager()).popData());
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState( SavedInstanceFragment.getInstance( getFragmentManager() ).popData() );
}

详细信息:http://www.devsbedevin.com/avoiding-transactiontoolargeexception-on-android-nougat-and-up/


9
投票

这个问题没有一个具体原因。对我来说,在我的Fragment类中,我这样做:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    View rootView = inflater.inflate(R.layout.snacks_layout, container); //<-- notice the absence of the false argument
    return rootView;
}

而不是这个:

View rootView = inflater.inflate(R.layout.softs_layout, container, false);

9
投票

将此添加到您的活动中

@Override
protected void onSaveInstanceState(Bundle oldInstanceState) {
    super.onSaveInstanceState(oldInstanceState);
    oldInstanceState.clear();
}

它对我有用,希望它也会对你有所帮助


8
投票

重要的是要了解事务缓冲区限制为1 MB,无论设备功能或应用程序如何。此缓冲区用于您进行的每个API调用,并在应用程序当前正在运行的所有事务中共享。

我相信它也有一些特定的对象,如parcels和(Parcel.obtain()),所以始终将每个obtain()recycle()相匹配非常重要。

即使返回的数据小于1 MB(如果其他事务仍在运行),返回大量数据的API调用也很容易发生此错误。

例如,PackageManager.getInstalledApplication()调用返回所有已安装应用程序的列表。添加特定标志允许检索大量额外数据。这样做可能会失败,因此建议不要检索任何额外的数据并按应用程序检索这些数据。

然而,呼叫可能仍然失败,因此用catch包围它并且必要时能够重试是很重要的。

据我所知,除了重试并确保尽可能少地检索信息之外,没有解决此类问题的方法。

© www.soinside.com 2019 - 2024. All rights reserved.