Android内存泄漏和垃圾回收 [英] Android Memory Leak and Garbage Collection

查看:92
本文介绍了Android内存泄漏和垃圾回收的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个片段,它始终引用父活动.在onCreateView方法上,我通过将静态列表传递给适配器来初始化适配器.由于列表是静态的",是否意味着将永远不会对Activity,Fragment和Adapter进行垃圾回收?

I have a fragment which keeps reference to the parent activity. On onCreateView method I initialise the adapter by passing a static list to the adapter. As the list is "static", does it mean that the Activity, Fragment and Adapter will never be garbage collected?

这是我的代码-

public class MyFragment extends Fragment 
{
RecyclerView rvMyContestLists;
MyContestListAdapter adapter = null;
Activity activity;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
{
        // CConstantVariables.listMyContestData is static
        adapter = new MyContestListAdapter(activity, CConstantVariables.listMyContestData);
        rvMyContestLists.setAdapter(adapter);
        rvMyContestLists.setLayoutManager(new LinearLayoutManager(getActivity()));
 }
 }

使用静态"变量CConstantVariables.listMyContestData作为适配器的列表数据是否意味着将永远不会收集垃圾活动?该代码是否表示内存泄漏?

Does using "static" variable CConstantVariables.listMyContestData as adapter's list data mean that the Activity will never be Garbage collected? Does this code indicates memory leak?

推荐答案

GC将收集未从 GC-root 对象引用的所有对象. GC-root 对象通常是:

The GC will collect all objects that aren't referenced from a GC-root object. The GC-root objects are typically:

  • 所有正在运行的线程
  • 所有静态字段

在您的示例中:CConstantVariables.listMyContestData是静态的,因此是潜在的内存泄漏源.您必须控制此列表的内容:

In your sample : CConstantVariables.listMyContestData is static and so a potential source of memory leak. You must keep the content of this list under control:

  • 确保此列表不包含不再需要的对象
  • 确保该列表中的对象不包含对您不再需要的对象的引用.

在适配器中使用静态列表不会阻止对适配器进行垃圾回收(一旦 GC根对象中不再有对适配器的引用).

Using a static list in the adapter won't prevent the adapter from being garbage collected (once there is no more references from GC-root objects to the adapter).

我建议您在跟踪Android中的内存泄漏方面做得很好: https://www. youtube.com/watch?v=_CruQY55HOk

I suggest you this very good talk about tracking memory leak in Android : https://www.youtube.com/watch?v=_CruQY55HOk

这篇关于Android内存泄漏和垃圾回收的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆