本文讲解android 开发中常见内存泄漏场景及其解决方案,内容包括代码示例、原因分析以及最佳实践建议。


1. 静态变量导致的内存泄漏
静态变量的生命周期与应用进程一致,如果静态变量持有了对 activity 或其他大对象的引用,就可能导致内存泄漏。
场景示例
public class memoryleakexample {
// 静态变量持有 activity 的引用
private static context scontext;
public static void setcontext(context context) {
scontext = context;
}
}
如果在 oncreate() 方法中调用了 memoryleakexample.setcontext(this),即使 activity 销毁,scontext 仍然持有对 activity 的引用,导致内存泄漏。
解决方案
- 避免使用静态变量持有对 context 的引用。
- 使用 applicationcontext 替代 activity 的 context。
修复代码
public class memoryleakexample {
private static context scontext;
public static void setcontext(context context) {
// 使用 applicationcontext 避免泄漏
scontext = context.getapplicationcontext();
}
}
2. handler 导致的内存泄漏
handler 会隐式持有外部类的引用,导致外部类无法被垃圾回收。
场景示例
public class mainactivity extends appcompatactivity {
private final handler handler = new handler(looper.getmainlooper()) {
@override
public void handlemessage(@nonnull message msg) {
// 处理消息
}
};
@override
protected void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
handler.postdelayed(() -> {
// 延迟任务
}, 10000);
}
}
如果在任务执行前 activity 被销毁,handler 仍然持有对 activity 的引用。
解决方案
- 将 handler 定义为静态内部类,避免隐式引用外部类。
- 使用弱引用(weakreference)来引用外部类。
修复代码
public class mainactivity extends appcompatactivity {
private static class myhandler extends handler {
private final weakreference activityreference;
public myhandler(mainactivity activity) {
super(looper.getmainlooper());
activityreference = new weakreference<>(activity);
}
@override
public void handlemessage(@nonnull message msg) {
mainactivity activity = activityreference.get();
if (activity != null) {
// 处理消息
}
}
}
private final myhandler handler = new myhandler(this);
@override
protected void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
handler.postdelayed(() -> {
// 延迟任务
}, 10000);
}
}
3. 非静态内部类持有外部类的引用
非静态内部类会隐式持有其外部类的引用,如果长时间持有,则可能导致内存泄漏。
场景示例
public class mainactivity extends appcompatactivity {
private class mytask extends asynctask {
@override
protected void doinbackground(void... voids) {
// 执行异步任务
return null;
}
}
@override
protected void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
new mytask().execute();
}
}
如果 mytask 执行时间较长,而 activity 已销毁,则会导致泄漏。
解决方案
- 将内部类声明为静态。
- 使用弱引用(weakreference)访问外部类实例。
修复代码
public class mainactivity extends appcompatactivity {
private static class mytask extends asynctask {
private final weakreference activityreference;
mytask(mainactivity activity) {
activityreference = new weakreference<>(activity);
}
@override
protected void doinbackground(void... voids) {
// 执行异步任务
return null;
}
@override
protected void onpostexecute(void avoid) {
mainactivity activity = activityreference.get();
if (activity != null) {
// 更新 ui
}
}
}
@override
protected void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
new mytask(this).execute();
}
}
4. 监听器或回调未正确移除
监听器或回调注册后,如果不及时移除,会导致对象无法释放。
场景示例
public class mainactivity extends appcompatactivity {
@override
protected void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
view view = findviewbyid(r.id.my_view);
view.addonattachstatechangelistener(new view.onattachstatechangelistener() {
@override
public void onviewattachedtowindow(view v) {
}
@override
public void onviewdetachedfromwindow(view v) {
}
});
}
}
如果未移除 onattachstatechangelistener,mainactivity 的引用可能被保留。
解决方案
在适当的生命周期方法中移除监听器或回调。
修复代码
public class mainactivity extends appcompatactivity {
private view.onattachstatechangelistener listener;
@override
protected void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
view view = findviewbyid(r.id.my_view);
listener = new view.onattachstatechangelistener() {
@override
public void onviewattachedtowindow(view v) {
}
@override
public void onviewdetachedfromwindow(view v) {
}
};
view.addonattachstatechangelistener(listener);
}
@override
protected void ondestroy() {
super.ondestroy();
view view = findviewbyid(r.id.my_view);
if (view != null && listener != null) {
view.removeonattachstatechangelistener(listener);
}
}
}
5. 单例模式导致的内存泄漏
单例对象的生命周期与应用一致,如果单例持有了对 context 或 activity 的引用,就会导致泄漏。
场景示例
public class singleton {
private static singleton instance;
private context context;
private singleton(context context) {
this.context = context;
}
public static singleton getinstance(context context) {
if (instance == null) {
instance = new singleton(context);
}
return instance;
}
}
在获取 singleton 时传入了 activity 的 context,会导致泄漏。
解决方案
- 使用 applicationcontext。
- 避免单例直接持有 context。
修复代码
public class singleton {
private static singleton instance;
private context context;
private singleton(context context) {
// 使用 applicationcontext 避免泄漏
this.context = context.getapplicationcontext();
}
public static singleton getinstance(context context) {
if (instance == null) {
instance = new singleton(context);
}
return instance;
}
}
6. 其他常见场景
6.1 bitmap 未及时回收
bitmap bitmap = bitmapfactory.decoderesource(getresources(), r.drawable.large_image); // 使用完毕后应回收 bitmap.recycle();
6.2 webview 泄漏
webview webview = new webview(context); webview.destroy();
以上示例涵盖了 android 中常见的内存泄漏场景及其解决方法,通过合理使用静态类、弱引用以及生命周期管理,可以有效减少内存泄漏问题。
到此这篇关于android中常见内存泄漏的场景和解决方案详解的文章就介绍到这了,更多相关android常见内存泄漏内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论