一个常见的android内存泄露 问题
来源:互联网 发布:人工智能猜人 编辑:程序博客网 时间:2024/04/29 13:52
存在内存泄露问题的一些代码片段像下面这样:
Util.java
public class Util {
private Context mContext;
private static Util sInstance;
private Util(Context context) {
this.mContext = context;
}
public static Util getInstance(Context context) {
if (sInstance == null) {
sInstance = new Util(context);
}
return sInstance;
}
//other methods
}
假设Activity A 里使用Util类:
Util.getInstance(this);
代码大意就是这样,这样写的问题就是,在Activity A 里使用Util类,传入的context 是 actvitiy-context。试想一下,当Activity A 生命周期结束,但Util类里面却还存在A的引用 (mContext),这样Activity A占用的内存就一直不能回收,而A的对象也不会再被使用。本人写代码测试过,在A中调用了finish(),A的destroy()方法也被执行了,但其占用的内存,比如说,ImageView占用的内存,还是不能释放的。有兴趣的话,可以自己测试一下。
那么如何解决这个问题呢?在A中,可以用Util.getInstance(getApplicationContext()); 或Util.getInstance(getApplication()); 代替。
因为Application的生命周期是贯穿整个程序的,所以Util类持有它的引用,也不会造成内存泄露问题。
其实这个问题android官方文档的Resources目录下的一篇题为
Avoiding Memory Leaks
的文章已经提到过。
可以自己去了解具体。
In summary, to avoid context-related memory leaks, remember the following:
- Do not keep long-lived references to a context-activity (a reference to an activity should have the same life cycle as the activity itself)
- Try using the context-application instead of a context-activity
- Avoid non-static inner classes in an activity if you don't control their life cycle, use a static inner class and make a weak reference to the activity inside. The solution to this issue is to use a static inner class with a to the outer class, as done in and its W inner class for instance
- A garbage collector is not an insurance against memory leaks
转自 http://xiechengfa.iteye.com/blog/1413688
- 一个常见的android内存泄露 问题
- 一个常见的android内存泄露 问题
- 一个常见的android内存泄露 问题
- android内存泄漏---常见内存泄露的问题
- Android 常见的内存泄露
- Android 常见内存泄露
- Android 常见内存泄露
- Android下常见的内存泄露
- Android下常见的内存泄露 经典
- Android下常见的内存泄露
- Android下常见的内存泄露
- Android下常见的内存泄露 经典
- Android下常见的内存泄露 经典
- Android下常见的内存泄露
- Android下常见的内存泄露
- Android下常见的内存泄露 经典
- Android下常见的内存泄露 经典
- Android下常见的内存泄露 经典
- #pragma pack字节对齐
- 以一种访问权限不允许的方式做了一个访问套接字的尝试 .
- linux软连接与硬连接的区别
- 软件随想录(local.joelonsoftware.com/wiki)-2003年10月08日 每个软件开发者都绝对一定要会的Unicode及字符集必备知识(没有借口!)
- JSP动作--JSP有三种注释方式
- 一个常见的android内存泄露 问题
- Android-需求(十):Setting之语言设置
- java.util.ResourceBundle使用详解
- ubuntu下安装mysql
- 论文写作中word操作
- unity开发插件,工具分享
- C++类成员的访问控制
- macro function sample
- 数据库基础学习-join