这是社交媒体应用程序的经典问题。如果您查看许多商业社交媒体应用程序,您将能够通过您提到的流程使其崩溃。 有关管理内存的一些想法是在添加片段时始终检查内存使用情况。当你达到某个限制时,或者决定颠覆以前的片段或者警告用户。 最大的问题之一是随着用户进一步深入研究每个片段中的内容。如果您在每个片段中加载了许多图片(这通常是社交媒体的情况),那么您可能会考虑在用户进一步导航时拍摄片段中保存的图片。当他们使用后退按钮返回时,片段将会然后从服务器重新加载图像。所以它的组合限制了碎片的数量以及碎片在内存中的内容。
还记得,当您使用后退按钮向后导航时,堆栈弹出不会从内存中删除片段。您还必须明确地调用remove,然后执行GC以确保在您回溯时删除东西。
在这里我有一个HashMap Stack的例子来保存与一个Tab关联的片段。像这样的,
private void popFragments(){
if(mStacks.get(currentTab)!=null && mStacks.get(currentTab).size()>1){
FragmentManager fm = getSupportFragmentManager();
Fragment currentFrag=mStacks.get(currentTab).pop();
// This is the part that will reclaim the memory
if(currentFrag.isAdded()){
fm.beginTransaction().detach(currentFrag).commit();
fm.beginTransaction().remove(currentFrag).commit();
}
currentFrag=null;
System.gc();
Fragment newFrag=mStacks.get(currentTab).lastElement();
if(newFrag !=null && newFrag.isAdded()){
fm.beginTransaction().attach(newFrag).commit();
}
else if(newFrag !=null && !newFrag.isAdded()){
fm.beginTransaction().add(R.id.fragment_content, newFrag,newFrag.getTag()).commit();
fm.beginTransaction().attach(newFrag).commit();
}
actionbar.setLargeTitle(newFrag.getTag());
}
}
祝你好运。
感谢您的回复。但我的问题是关于片段,而不是活动。 – XWang
其中有相同的... – safari
对于一个活动,我可以设置启动模式和标志。但对于片段,我该怎么做?非常感谢。 – XWang