打开和关闭活动时内存堆大小不断增加

时间:2018-10-22 07:57:41

标签: android heap-memory

我从A启动活动B。然后销毁B活动。然后,我再次从A启动活动B,依此类推。当我这样做时,我的堆大小每次都会增加约0.5 MB。我使用android profiler,当活动B被杀死后,我强制从android profiler进行垃圾收集。问题是GB之后的堆大小没有减少。另外我的代码是上面的,是来自android studio的通用代码。如果有问题,我如何通过堆转储看到它?它显示了很多分配,我不理解。

MainActivity

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            startActivity(newIntent(MainActivity.this,Main2Activity.class));
        }
    });
}

MainActivity2

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

检查Logheap:

 Log.d("tag", "debug. =================================");
                Log.d("tag", "debug.heap native: allocated " + df.format(allocated) + "MB of " + df.format(available) + "MB (" + df.format(free) + "MB free)");
                Log.d("tag", "debug.memory: allocated: " + df.format(new Double(Runtime.getRuntime().totalMemory() / 1048576.0)) + "MB of " + df.format(new Double(Runtime.getRuntime().maxMemory() / 1048576.0)) + "MB (" + df.format(new Double(Runtime.getRuntime().freeMemory() / 1048576.0)) + "MB free)");

1 个答案:

答案 0 :(得分:1)

转储您的内存信息,并在MainActivity2完成多次之后(如果计数大于0等于您启动它的次数)后返回ckeck实例计数,这意味着存在内存泄漏问题,或者计数为零,然后忽略它。

编辑: 添加图片,列分配数是实例计数,找到活动并检查dumpinfo