如何清除以前布局的图片中的内存?转到不同的布局/活动时如何清理内存? [英] How to clear memory from pictures of previous layouts? How to clean memory when go to different layout/activity?

查看:79
本文介绍了如何清除以前布局的图片中的内存?转到不同的布局/活动时如何清理内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序由4个布局文件组成,每个布局使用不同的图像作为背景.我设法加载布局1和2,但是转到布局3后,出现错误"Caused by:java.lang.OutOfMemoryError"

My app consists from 4 layout files, each layout uses a different image as background. I manage to load layout 1 and 2, but after I go to layout 3 I get error "Caused by: java.lang.OutOfMemoryError"

我怀疑这是因为布局1和布局2仍在内存中.有什么方法可以在每次使用新布局时清理内存,以免内存用完吗?谢谢.

I suspect it's because the layout 1 and layout 2 is still in the memory. Any way is there a way to clean memory everytime I go to a new layout so I don't run out of memory? Thanks.

我使用Android Studio.

P.S I use Android Studio.

P.S 2我不确定这是否会改变任何东西,但以防万一,这是我去不同的活动/布局的方式:

P.S 2 I'm not sure if this changes anything but just in case this is how I go to different activities/layouts:

previouspage.setOnClickListener(
                new Button.OnClickListener() {
                    public void onClick(View v) {
                        Intent intent = new Intent(v.getContext(), secondPage.class);
                        startActivity(intent);
                    }
                }
        );

        nextpage.setOnClickListener(
                new Button.OnClickListener() {
                    public void onClick(View v) {
                        Intent intent = new Intent(v.getContext(), FourthPage.class);
                        startActivity(intent);
                    }
                }
        );

推荐答案

new Button.OnClickListener() {
      public void onClick(View v) {
         Intent intent = new Intent(v.getContext(), secondPage.class);
         startActivity(intent);

         yourExistingActivity.finish();  // This will free the memory

}

请注意,您从中调用finish()方法的活动已销毁,并且 ALL 其资源已被排队以进行垃圾收集,以及此活动将在下一个GC周期期间释放.

Note that the activity you're calling the finish() method from is destroyed and ALL its resources are queued for garbage collection, and all memory that was used by this activity will be freed during next GC cycle.

如果您真的想尽快撤消内存,请覆盖您活动的onDestroy方法:

If you really want to revoke the memory as soon as possible, override your activities' onDestroy method:

@Override
public void onDestroy() {
    super.onDestroy();
    Runtime.getRuntime().gc();      
}

这篇关于如何清除以前布局的图片中的内存?转到不同的布局/活动时如何清理内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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