2013-01-03 23 views
1

我正在开发一个带有几个片段的社交应用程序。有一个包含网格视图的朋友片段。如果我点击一个项目,然后打开一个配置文件片段,并将其添加到背堆栈。然后在配置文件片段中,用户仍然可以输入一个新的Friend片段,并将其添加到后端堆栈中,等等。所以后端堆栈可以是朋友a - >个人资料b - >朋友c - >个人资料d - >朋友e - > Profile f - > ...如何减少使用带栈栈的内存使用率?

所以我的问题是,由于用户可以输入几个级别,并将几个片段放入后端堆栈,并且一些片段有很多图像视图,如何减少内存使用情况并避免OOE?

在此先感谢。

回答

2

你可能只有一个真正的方法 - 限制后面的堆栈!这里有一个职位,你如何能做到这一点:How to limit the number of the same Activity on the stack for an Android application

问候

野生动物园

PS:又到这里看看:这里http://developer.android.com/guide/components/tasks-and-back-stack.html


你看,这是你需要做什么:

FragmentManager fm = getActivity().getSupportFragmentManager(); 
for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {  
    fm.popBackStack(); 
} 

你也可以我们e像这样:

FragmentManager.popBackStack(String name, FragmentManager.POP_BACK_STACK_INCLUSIVE) 

希望这会有所帮助。

最好的问候

+0

感谢您的回复。但我的问题是关于片段,而不是活动。 – XWang

+0

其中有相同的... – safari

+0

对于一个活动,我可以设置启动模式和标志。但对于片段,我该怎么做?非常感谢。 – XWang

1

这是社交媒体应用程序的经典问题。如果您查看许多商业社交媒体应用程序,您将能够通过您提到的流程使其崩溃。 有关管理内存的一些想法是在添加片段时始终检查内存使用情况。当你达到某个限制时,或者决定颠覆以前的片段或者警告用户。 最大的问题之一是随着用户进一步深入研究每个片段中的内容。如果您在每个片段中加载了许多图片(这通常是社交媒体的情况),那么您可能会考虑在用户进一步导航时拍摄片段中保存的图片。当他们使用后退按钮返回时,片段将会然后从服务器重新加载图像。所以它的组合限制了碎片的数量以及碎片在内存中的内容。

还记得,当您使用后退按钮向后导航时,堆栈弹出不会从内存中删除片段。您还必须明确地调用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()); 
    } 
} 

祝你好运。