Nougat上的android.os.TransactionTooLargeException

问题描述 投票:69回答:13

我将Nexus 5X更新为Android N,现在当我在其上安装应用程序(调试或发布)时,我在每个具有附加功能的Bundle的屏幕转换上都会收到TransactionTooLargeException。该应用正在处理所有其他设备。 PlayStore上的旧应用程序和大多数相同的代码正在使用Nexus 5X。有人有同样的问题吗?

java.lang.RuntimeException: android.os.TransactionTooLargeException: data parcel size 592196 bytes
   at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3752)
   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:6077)
   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 592196 bytes
   at android.os.BinderProxy.transactNative(Native Method)
   at android.os.BinderProxy.transact(Binder.java:615)
   at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3606)
   at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3744)
   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:6077) 
   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) 
android android-7.0-nougat
13个回答
26
投票

每当你看到TransactionTooLargeException正在停止时发生Activity,这意味着Activity试图将其保存的状态Bundles发送到系统操作系统以便以后安全保存(在配置更改或进程死亡后)但是或者它发送的更多Bundles太大了。对于同时发生的所有此类交易,最大限制大约为1MB,即使没有单个Bundle超过该限制,也可以达到该限制。

这里的主要罪魁祸首通常是在onSaveInstanceState或由Activity主办的任何FragmentsActivity中保存太多数据。通常情况下,这会在保存像Bitmap这样特别大的东西时发生,但在发送大量较小的数据时也会发生这种情况,例如Parcelable对象的列表。 Android团队在很多场合都非常明确地表示,在onSavedInstanceState中只能保存少量与视图相关的数据。但是,开发人员经常保存网络数据页面,以便通过不必再次重新获取相同数据来使配置更改显得尽可能平滑。从Google I / O 2017开始,Android团队已经明确表示Android应用程序的首选架构可以节省网络数据

  • 在内存中,因此可以在配置更改中轻松重用
  • 到磁盘,以便在进程死亡和应用程序会话后可以轻松恢复

他们新的ViewModel框架和Room持久性库旨在帮助开发人员适应这种模式。如果您的问题是在onSaveInstanceState中保存了太多数据,那么使用这些工具更新到这样的架构应该可以解决您的问题。

就个人而言,在更新到新模式之前,我想采用我现有的应用程序,并在此期间绕过TransactionTooLargeException。我写了一个快速库来做到这一点:https://github.com/livefront/bridge。它使用了相同的一般想法,即从内存中恢复配置更改中的状态,以及在进程死亡后从磁盘恢复状态,而不是通过onSaveInstanceState将所有状态发送到操作系统,但需要对现有代码进行非常小的更改才能使用。任何符合这两个目标的策略应该可以帮助您避免异常,同时不会牺牲您保存状态的能力。

最后请注意:你在Nougat +上看到这个的唯一原因是,如果超过了绑定器事务限制,那么将保存状态发送到操作系统的过程将无声地失败,只有在Logcat中出现此错误:

!失败的粘合剂交易!

在Nougat,这种沉默的失败升级为严重的崩溃。值得赞扬的是,这是开发团队在the release notes for Nougat中记录的内容:

许多平台API现在已经开始检查通过Binder事务发送的大型有效负载,系统现在将TransactionTooLargeExceptions重新抛出为RuntimeExceptions,而不是静默记录或抑制它们。一个常见示例是在Activity.onSaveInstanceState()中存储过多数据,这会导致ActivityThread.StopInfo在您的应用针对Android 7.0时抛出RuntimeException。


1
投票

我遇到了同样的问题。我的解决方法将savedInstanceState卸载到缓存目录中的文件。

我做了以下实用程序类。

package net.cattaka.android.snippets.issue;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * To parry BUG of Android N. https://code.google.com/p/android/issues/detail?id=212316
 * <p>
 * Created by cattaka on 2017/01/12.
 */
public class Issue212316Parrier {
    public static final String DEFAULT_NAME = "Issue212316Parrier";
    private static final String KEY_STORED_BUNDLE_ID = "net.cattaka.android.snippets.issue.Issue212316Parrier.KEY_STORED_BUNDLE_ID";

    private String mName;
    private Context mContext;
    private String mAppVersionName;
    private int mAppVersionCode;
    private SharedPreferences mPreferences;
    private File mDirForStoredBundle;

    public Issue212316Parrier(Context context, String appVersionName, int appVersionCode) {
        this(context, appVersionName, appVersionCode, DEFAULT_NAME);
    }

    public Issue212316Parrier(Context context, String appVersionName, int appVersionCode, String name) {
        mName = name;
        mContext = context;
        mAppVersionName = appVersionName;
        mAppVersionCode = appVersionCode;
    }

    public void initialize() {
        mPreferences = mContext.getSharedPreferences(mName, Context.MODE_PRIVATE);

        File cacheDir = mContext.getCacheDir();
        mDirForStoredBundle = new File(cacheDir, mName);
        if (!mDirForStoredBundle.exists()) {
            mDirForStoredBundle.mkdirs();
        }

        long lastStoredBundleId = 1;
        boolean needReset = true;
        String fingerPrint = (Build.FINGERPRINT != null) ? Build.FINGERPRINT : "";
        needReset = !fingerPrint.equals(mPreferences.getString("deviceFingerprint", null))
                || !mAppVersionName.equals(mPreferences.getString("appVersionName", null))
                || (mAppVersionCode != mPreferences.getInt("appVersionCode", 0));
        lastStoredBundleId = mPreferences.getLong("lastStoredBundleId", 1);

        if (needReset) {
            clearDirForStoredBundle();

            mPreferences.edit()
                    .putString("deviceFingerprint", Build.FINGERPRINT)
                    .putString("appVersionName", mAppVersionName)
                    .putInt("appVersionCode", mAppVersionCode)
                    .putLong("lastStoredBundleId", lastStoredBundleId)
                    .apply();
        }
    }

    /**
     * Call this from {@link android.app.Activity#onCreate(Bundle)}, {@link android.app.Activity#onRestoreInstanceState(Bundle)} or {@link android.app.Activity#onPostCreate(Bundle)}
     */
    public void restoreSaveInstanceState(@Nullable Bundle savedInstanceState, boolean deleteStoredBundle) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            if (savedInstanceState != null && savedInstanceState.containsKey(KEY_STORED_BUNDLE_ID)) {
                long storedBundleId = savedInstanceState.getLong(KEY_STORED_BUNDLE_ID);
                File storedBundleFile = new File(mDirForStoredBundle, storedBundleId + ".bin");
                Bundle storedBundle = loadBundle(storedBundleFile);
                if (storedBundle != null) {
                    savedInstanceState.putAll(storedBundle);
                }
                if (deleteStoredBundle && storedBundleFile.exists()) {
                    storedBundleFile.delete();
                }
            }
        }
    }

    /**
     * Call this from {@link android.app.Activity#onSaveInstanceState(Bundle)}
     */
    public void saveInstanceState(Bundle outState) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            if (outState != null) {
                long nextStoredBundleId = mPreferences.getLong("lastStoredBundleId", 1) + 1;
                mPreferences.edit().putLong("lastStoredBundleId", nextStoredBundleId).apply();
                File storedBundleFile = new File(mDirForStoredBundle, nextStoredBundleId + ".bin");
                saveBundle(outState, storedBundleFile);
                outState.clear();
                outState.putLong(KEY_STORED_BUNDLE_ID, nextStoredBundleId);
            }
        }
    }

    private void saveBundle(@NonNull Bundle bundle, @NonNull File storedBundleFile) {
        byte[] blob = marshall(bundle);
        OutputStream out = null;
        try {
            out = new GZIPOutputStream(new FileOutputStream(storedBundleFile));
            out.write(blob);
            out.flush();
            out.close();
        } catch (IOException e) {
            // ignore
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    // ignore
                }
            }
        }
    }

    @Nullable
    private Bundle loadBundle(File storedBundleFile) {
        byte[] blob = null;
        InputStream in = null;
        try {
            in = new GZIPInputStream(new FileInputStream(storedBundleFile));
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            int n;
            byte[] buffer = new byte[1024];
            while ((n = in.read(buffer)) > -1) {
                bout.write(buffer, 0, n);   // Don't allow any extra bytes to creep in, final write
            }
            bout.close();
            blob = bout.toByteArray();
        } catch (IOException e) {
            // ignore
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    // ignore
                }
            }
        }

        try {
            return (blob != null) ? (Bundle) unmarshall(blob) : null;
        } catch (Exception e) {
            return null;
        }
    }

    private void clearDirForStoredBundle() {
        for (File file : mDirForStoredBundle.listFiles()) {
            if (file.isFile() && file.getName().endsWith(".bin")) {
                file.delete();
            }
        }
    }


    @NonNull
    private static <T extends Parcelable> byte[] marshall(@NonNull final T object) {
        Parcel p1 = Parcel.obtain();
        p1.writeValue(object);

        byte[] data = p1.marshall();
        p1.recycle();
        return data;
    }

    @SuppressWarnings("unchecked")
    @NonNull
    private static <T extends Parcelable> T unmarshall(@NonNull byte[] bytes) {
        Parcel p2 = Parcel.obtain();
        p2.unmarshall(bytes, 0, bytes.length);
        p2.setDataPosition(0);
        T result = (T) p2.readValue(Issue212316Parrier.class.getClassLoader());
        p2.recycle();
        return result;
    }
}

完整代码:https://github.com/cattaka/AndroidSnippets/pull/37

我担心Parcel#marshall不应该用于持久性。但是,我没有任何其他想法。


1
投票

上述答案都没有对我有用,问题的原因非常简单,正如我所说的那样,我使用了FragmentStatePagerAdapter,它的saveState方法保存了片段的状态,因为我的一个片段非常大,所以保存了这个片段导致此TransactionTooLargeExecption。

我试图在@ IK828所述的pager实现中覆盖saveState方法,但这无法解决崩溃问题。

我的片段有一个EditText,用于保存非常大的文本,这是我案例中问题的罪魁祸首,所以简单地在片段的onPause()中,我将edittext文本设置为空字符串。即:

@Override
    public void onPause() {
       edittext.setText("");
}

现在,当FragmentStatePagerAdapter尝试saveState时,这一大块文本将不会占用更多的部分,从而解决了崩溃问题。

在你的情况下,你需要找到任何罪魁祸首,它可能是带有一些位图的ImageView,带有大量文本的TextView或任何其他高内存消耗视图,你需要释放它的内存,你可以设置imageview.setImageResource(您的片段的onPause()中的null)或类似内容。

更新:onSaveInstanceState在调用super之前是更好的地方,如:

@Override
    public void onSaveInstanceState(Bundle outState) {
        edittext.setText("");
        super.onSaveInstanceState(outState);
    }

或者@Vladimir指出你可以使用android:saveEnabled =“false”或view.setSaveEnabled(false);在视图或自定义视图上,并确保将文本设置回onResume,否则当Activity恢复时它将为空。


0
投票

由于Android N更改了行为并抛出TransactionTooLargeException而不是记录错误。

     try {
            if (DEBUG_MEMORY_TRIM) Slog.v(TAG, "Reporting activity stopped: " + activity);
            ActivityManagerNative.getDefault().activityStopped(
                activity.token, state, persistentState, description);
        } catch (RemoteException ex) {
            if (ex instanceof TransactionTooLargeException
                    && activity.packageInfo.getTargetSdkVersion() < Build.VERSION_CODES.N) {
                Log.e(TAG, "App sent too much data in instance state, so it was ignored", ex);
                return;
            }
            throw ex.rethrowFromSystemServer();
        }

我的解决方案是挂钩ActivityMangerProxy实例并尝试捕获activityStopped方法。

这是代码:

private boolean hookActivityManagerNative() {
    try {
        ClassLoader loader = ClassLoader.getSystemClassLoader();
        Field singletonField = ReflectUtils.findField(loader.loadClass("android.app.ActivityManagerNative"), "gDefault");
        ReflectUtils.ReflectObject singletonObjWrap = ReflectUtils.wrap(singletonField.get(null));
        Object realActivityManager = singletonObjWrap.getChildField("mInstance").get();
        Object fakeActivityManager = Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(),
                new Class[]{loader.loadClass("android.app.IActivityManager")}, new ActivityManagerHook(realActivityManager));
        singletonObjWrap.setChildField("mInstance", fakeActivityManager);
        return true;
    } catch (Throwable e) {
        AppHolder.getThirdPartUtils().markException(e);
        return false;
    }
}

private static class ActivityManagerHook implements InvocationHandler {

    private Object origin;

    ActivityManagerHook(Object origin) {
       this.origin = origin;
    }

    public Object getOrigin() {
        return origin;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        switch (method.getName()) {
            //ActivityManagerNative.getDefault().activityStopped(activity.token, state, persistentState, description);
            case "activityStopped": {
                try {
                    return method.invoke(getOrigin(), args);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        }
        return method.invoke(getOrigin(), args);
    }
}

反射助手类是

public class ReflectUtils {

private static final HashMap<String, Field> fieldCache = new HashMap<>();
private static final HashMap<String, Method> methodCache = new HashMap<>();

public static Field findField(Class<?> clazz, String fieldName) throws Throwable {
    String fullFieldName = clazz.getName() + '#' + fieldName;

    if (fieldCache.containsKey(fullFieldName)) {
        Field field = fieldCache.get(fullFieldName);
        if (field == null)
            throw new NoSuchFieldError(fullFieldName);
        return field;
    }

    try {
        Field field = findFieldRecursiveImpl(clazz, fieldName);
        field.setAccessible(true);
        fieldCache.put(fullFieldName, field);
        return field;
    } catch (NoSuchFieldException e) {
        fieldCache.put(fullFieldName, null);
        throw new NoSuchFieldError(fullFieldName);
    }
}


private static Field findFieldRecursiveImpl(Class<?> clazz, String fieldName) throws NoSuchFieldException {
    try {
        return clazz.getDeclaredField(fieldName);
    } catch (NoSuchFieldException e) {
        while (true) {
            clazz = clazz.getSuperclass();
            if (clazz == null || clazz.equals(Object.class))
                break;

            try {
                return clazz.getDeclaredField(fieldName);
            } catch (NoSuchFieldException ignored) {
            }
        }
        throw e;
    }
}


public static Method findMethodExact(Class<?> clazz, String methodName, Class<?>... parameterTypes) throws Throwable {
    String fullMethodName = clazz.getName() + '#' + methodName + getParametersString(parameterTypes) + "#exact";

    if (methodCache.containsKey(fullMethodName)) {
        Method method = methodCache.get(fullMethodName);
        if (method == null)
            throw new NoSuchMethodError(fullMethodName);
        return method;
    }

    try {
        Method method = clazz.getDeclaredMethod(methodName, parameterTypes);
        method.setAccessible(true);
        methodCache.put(fullMethodName, method);
        return method;
    } catch (NoSuchMethodException e) {
        methodCache.put(fullMethodName, null);
        throw new NoSuchMethodError(fullMethodName);
    }
}


/**
 * Returns an array of the given classes.
 */
public static Class<?>[] getClassesAsArray(Class<?>... clazzes) {
    return clazzes;
}

private static String getParametersString(Class<?>... clazzes) {
    StringBuilder sb = new StringBuilder("(");
    boolean first = true;
    for (Class<?> clazz : clazzes) {
        if (first)
            first = false;
        else
            sb.append(",");

        if (clazz != null)
            sb.append(clazz.getCanonicalName());
        else
            sb.append("null");
    }
    sb.append(")");
    return sb.toString();
}

/**
 * Retrieve classes from an array, where each element might either be a Class
 * already, or a String with the full class name.
 */
private static Class<?>[] getParameterClasses(ClassLoader classLoader, Object[] parameterTypes) throws ClassNotFoundException {
    Class<?>[] parameterClasses = null;
    for (int i = parameterTypes.length - 1; i >= 0; i--) {
        Object type = parameterTypes[i];
        if (type == null)
            throw new ClassNotFoundException("parameter type must not be null", null);

        if (parameterClasses == null)
            parameterClasses = new Class<?>[i + 1];

        if (type instanceof Class)
            parameterClasses[i] = (Class<?>) type;
        else if (type instanceof String)
            parameterClasses[i] = findClass((String) type, classLoader);
        else
            throw new ClassNotFoundException("parameter type must either be specified as Class or String", null);
    }

    // if there are no arguments for the method
    if (parameterClasses == null)
        parameterClasses = new Class<?>[0];

    return parameterClasses;
}

public static Class<?> findClass(String className, ClassLoader classLoader) throws ClassNotFoundException {
    if (classLoader == null)
        classLoader = ClassLoader.getSystemClassLoader();
    return classLoader.loadClass(className);
}


public static ReflectObject wrap(Object object) {
    return new ReflectObject(object);
}


public static class ReflectObject {

    private Object object;

    private ReflectObject(Object o) {
        this.object = o;
    }

    public ReflectObject getChildField(String fieldName) throws Throwable {
        Object child = ReflectUtils.findField(object.getClass(), fieldName).get(object);
        return ReflectUtils.wrap(child);
    }

    public void setChildField(String fieldName, Object o) throws Throwable {
        ReflectUtils.findField(object.getClass(), fieldName).set(object, o);
    }

    public ReflectObject callMethod(String methodName, Object... args) throws Throwable {
        Class<?>[] clazzs = new Class[args.length];
        for (int i = 0; i < args.length; i++) {
            clazzs[i] = args.getClass();
        }
        Method method = ReflectUtils.findMethodExact(object.getClass(), methodName, clazzs);
        return ReflectUtils.wrap(method.invoke(object, args));
    }

    public <T> T getAs(Class<T> clazz) {
        return (T) object;
    }

    public <T> T get() {
        return (T) object;
    }
}
}

0
投票

在我的情况下,我使用TooLargeTool来追踪问题的来源,我发现android:support:fragments中的Bundle密钥来自我的onSaveInstanceState,当应用程序崩溃时曾经达到差不多1mb。所以解决方案就像:

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.remove("android:support:fragments");
}

通过这样做,我避免保存所有碎片的状态,并保留其他需要保存的东西。


25
投票

最后,我的问题是保存在SaveInstance上的事情,而不是发送到下一个活动的事情。我删除了无法控制对象大小的所有保存(网络响应),现在它正在工作。

更新:

为了保留大块数据,Google建议使用保留实例的Fragment来实现。想法是创建空片段而不包含所有必需字段的视图,否则将保存在Bundle中。将setRetainInstance(true);添加到Fragment的onCreate方法中。然后将数据保存在Activity的onDestroy上的Fragment中并将它们加载到onCreate上。以下是活动的示例:

public class MyActivity extends Activity {

    private DataFragment dataFragment;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // find the retained fragment on activity restarts
        FragmentManager fm = getFragmentManager();
        dataFragment = (DataFragment) fm.findFragmentByTag(“data”);

        // create the fragment and data the first time
        if (dataFragment == null) {
            // add the fragment
            dataFragment = new DataFragment();
            fm.beginTransaction().add(dataFragment, “data”).commit();
            // load the data from the web
            dataFragment.setData(loadMyData());
        }

        // the data is available in dataFragment.getData()
        ...
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // store the data in the fragment
        dataFragment.setData(collectMyLoadedData());
    }
}

片段的例子:

public class DataFragment extends Fragment {

    // data object we want to retain
    private MyDataObject data;

    // this method is only called once for this fragment
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // retain this fragment
        setRetainInstance(true);
    }

    public void setData(MyDataObject data) {
        this.data = data;
    }

    public MyDataObject getData() {
        return data;
    }
}

更多关于它,你可以阅读here


18
投票

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

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

虽然我们在destroyItem()中正确管理了片段,但是在FragmentStatePagerAdapter的Androids实现中有一个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。当该数组被转储到parcelableArray并且操作系统不喜欢100多个项目时,就会发生TransactionTooLargeException。

因此,我们的修复是覆盖saveState()方法而不是为“状态”存储任何内容。

@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;
}

14
投票

受到了打击和审判,最后这解决了我的问题。将此添加到您的Activity

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

10
投票

我在Nougat设备上也遇到了这个问题。我的应用程序使用带有视图寻呼机的片段,其中包含4个片段。我将一些大的构造参数传递给造成问题的4个碎片。

我在Bundle的帮助下追踪了TooLargeTool的大小。

最后,我在POJO对象上使用putSerializable解决了它,它实现了Serializable,而不是在片段初始化期间使用String传递大的原始putString。这使Bundle的尺寸缩小了一半,并没有抛出TransactionTooLargeException。因此,请确保您没有将大尺寸参数传递给Fragment

附: Google问题跟踪器中的相关问题:https://issuetracker.google.com/issues/37103380


8
投票

我面临类似的问题。问题和情况略有不同,我通过以下方式解决它。请检查方案和解决方案。

场景:我在谷歌Nexus 6P设备(7操作系统)中遇到了一个奇怪的错误,因为我的应用程序将在工作4小时后崩溃。后来我发现它正在抛出类似的(android.os.TransactionTooLargeException :)异常。

解决方案:日志没有指向应用程序中的任何特定类,后来我发现这是因为保留了后端堆栈的碎片。在我的例子中,借助自动屏幕移动动画,将4个片段重复添加到后栈。所以我重写onBackstackChanged()如下所述。

 @Override
    public void onBackStackChanged() {
        try {
            int count = mFragmentMngr.getBackStackEntryCount();
            if (count > 0) {
                if (count > 30) {
                    mFragmentMngr.popBackStack(1, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                    count = mFragmentMngr.getBackStackEntryCount();
                }
                FragmentManager.BackStackEntry entry = mFragmentMngr.getBackStackEntryAt(count - 1);
                mCurrentlyLoadedFragment = Integer.parseInt(entry.getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

如果堆栈超出限制,它将自动弹出到初始片段。我希望有人会帮助这个答案,因为异常和堆栈跟踪日志是相同的。因此,无论何时发生此问题,请检查后台堆栈计数,如果您正在使用碎片和后台堆栈。


5
投票

在我的情况下,我在一个片段中得到了这个异常,因为它的一个参数是一个非常大的字符串,我忘了删除它(我只在onViewCreated()方法中使用了那个大字符串)。所以,为了解决这个问题,我简单地删除了这个论点。在您的情况下,您必须在调用onPause()之前清除或取消任何可疑字段。

活动代码

Fragment fragment = new Fragment();
Bundle args = new Bundle();
args.putString("extremely large string", data.getValue());
fragment.setArguments(args);

片段代码

@Override 
public void onViewCreated(View view, Bundle savedInstanceState) {

    String largeString = arguments.get("extremely large string");       
    //Do Something with the large string   
    arguments.clear() //I forgot to execute this  
}

2
投票

我的应用程序中的问题是我试图在savedInstanceState中保存太多,解决方案是确切地确定应该在正确的时间保存哪些数据。基本上仔细查看你的onSaveInstanceState以确保你不会拉伸它:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the user's current state
    // Check carefully what you're adding into the savedInstanceState before saving it
    super.onSaveInstanceState(savedInstanceState);
}

1
投票

只需在您的活动上覆盖此方法:

@Override
protected void onSaveInstanceState(Bundle outState) {
    // below line to be commented to prevent crash on nougat.
    // http://blog.sqisland.com/2016/09/transactiontoolargeexception-crashes-nougat.html
    //
    //super.onSaveInstanceState(outState);
}

有关更多信息,请访问https://code.google.com/p/android/issues/detail?id=212316#makechanges

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