片段backstack使用太多内存

时间:2016-03-29 14:07:03

标签: android android-fragments android-memory fragment-backstack

我正在开发一个相当大的应用程序(大约70个片段)。当我点击我的应用程序时,我以前的所有片段都存储在后台堆栈中。经过一些点击后,我的内存非常高,在旧手机(三星S3)上,我得到一个OutOfMemory异常。

有没有办法对片段backstack的内存使用做些什么? 我已经尝试制作自己的后台堆栈,它修复了内存问题,但唯一的问题是它不记得搜索条件和滚动位置:

Stack<BackStackEntry> mBackStack = new Stack<>();
mBackStack.add(new BackStackEntry(tag, fragment.getClass()));

2 个答案:

答案 0 :(得分:0)

您可以为片段使用SingleTone模式。至少会减少内存肯定,因为你不必每次调用时都重新创建片段或者在后台添加它

 // Singleton implementation
    private static YourFragment instance;

    public YourFragment () {
    }

    /**
     * Static method which return the instance of the fragment. If the fragment is null, load it,
     * else create new fragment. Singleton pattern.
     *
     * @param context
     * @return
     */
    public static YourFragment getInstance() {
        if (instance == null) {
            instance = new YourFragment ();
        }

        return instance;
    }

您可以使用以下代码访问您的片段:

SearchFragment.getInstance()

答案 1 :(得分:0)

  

在非常特殊的情况下,您可以请求更大的堆大小   在清单中将largeHeap属性设置为“true”    标签。永远不要因为你的原因而要求大堆   内存耗尽而你需要快速修复 - 你应该只在使用它时使用它   你确切地知道所有内存的分配位置以及原因   必须保留。

阅读https://developer.android.com/training/articles/memory.html

相关问题