Android 如何在使用带后堆栈的片段时减少内存使用?
我正在开发一个包含几个片段的社交应用程序。有一个朋友片段包含一个网格视图。若我单击一个项目,然后打开一个概要文件片段,并将其添加到后堆栈中。然后在概要文件片段中,用户仍然可以输入一个新的朋友片段,并将其添加到后堆栈中,等等。因此,后堆栈可以是朋友a->概要文件b->朋友c->概要文件d->朋友e->概要文件f-> 所以我的问题是,既然用户可以进入多个级别,并将多个片段放入后堆栈,并且其中一些片段有很多图像视图,那么如何减少内存使用并避免OOEAndroid 如何在使用带后堆栈的片段时减少内存使用?,android,memory,fragment,out-of-memory,Android,Memory,Fragment,Out Of Memory,我正在开发一个包含几个片段的社交应用程序。有一个朋友片段包含一个网格视图。若我单击一个项目,然后打开一个概要文件片段,并将其添加到后堆栈中。然后在概要文件片段中,用户仍然可以输入一个新的朋友片段,并将其添加到后堆栈中,等等。因此,后堆栈可以是朋友a->概要文件b->朋友c->概要文件d->朋友e->概要文件f-> 所以我的问题是,既然用户可以进入多个级别,并将多个片段放入后堆栈,并且其中一些片段有很多图像视图,那么如何减少内存使用并避免OOE 提前感谢。您的应用程序可能只有一种真正的方法—限制后
提前感谢。您的应用程序可能只有一种真正的方法—限制后堆栈!这里有一个帖子,告诉你如何做到这一点: 致意 狩猎 附言:请看这里:
看这里,这就是你需要做的:
FragmentManager fm = getActivity().getSupportFragmentManager();
for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {
fm.popBackStack();
}
希望这有帮助
这是社交媒体应用程序的一个典型问题。如果你看看许多商业社交媒体应用程序,你将能够在你提到的过程中使它们崩溃。 管理内存的一些想法是在添加片段时始终检查内存使用情况。当你达到某个极限时,要么决定重击前面的片段,要么警告用户。 最大的问题之一是,随着用户深入研究,每个片段中都有什么内容。如果在每个片段中加载了许多图像(通常是社交媒体的情况),那么当用户进一步导航时,您可能会考虑在碎片中保留图像。当他们使用back按钮返回时,片段将从服务器重新加载图像。因此,它既限制了片段的绝对数量,也限制了片段在堆栈中的内容 还要记住,当您使用后退按钮向后导航时,堆栈弹出窗口不会从内存中删除片段。您还必须显式地调用remove,然后执行GC,以确保在回溯时删除内容 这里我有一个HashMap堆栈的示例,用于保存与选项卡关联的片段。像这样的,
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());
}
}
祝你好运。谢谢你的回复。但我的问题是关于片段,而不是活动。对于活动,我可以设置启动模式和标志。但对于fragment,我该怎么做呢?非常感谢。它解决了我的问题。节省了我的时间。谢谢……:)
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());
}
}