博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
android内存泄露
阅读量:6905 次
发布时间:2019-06-27

本文共 1091 字,大约阅读时间需要 3 分钟。

hot3.png

##一.(非静态)内部类引起内存泄漏的原因(Handler) #####Activity内handler本身支持activity对象,所以在 public void handleMessage(Message msg) {}能进行view的操作,所以当发生GC时候,activity由于handler的引用无法释放,进而造成内存泄露。 #####解决方案:静态内部类+弱引用,如下: public class MainActivity extends Activity { private Handler mHandler = new MyHandler(this); public TextView textView; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); textView = new TextView(this); textView.setText("hellow"); setContentView(textView); mHandler.sendMessageDelayed(Message.obtain(), 2000); } private static class MyHandler extends Handler { private WeakReference<MainActivity> mWeakReference; public MyHandler(MainActivity activity) { mWeakReference = new WeakReference<MainActivity>(activity); } "@Override" public void handleMessage(Message msg) { MainActivity activity = mWeakReference.get(); if (activity != null) activity.textView.setText("静态内部类的Handler"); } } "@Override" protected void onDestroy() { super.onDestroy(); if (mHandler != null) mHandler.removeCallbacksAndMessages(null); } }

转载于:https://my.oschina.net/u/435726/blog/1512151

你可能感兴趣的文章
The direct sum of functions
查看>>
微软职位内部推荐-Senior Software Engineer
查看>>
《Linux内核设计与实现》读书笔记(十五)- 进程地址空间(kernel 2.6.32.60)
查看>>
codevs1026
查看>>
CXF支持 SOAP1.1 SOAP1.2协议
查看>>
vue 开发系列(二) vue ajax 拦截
查看>>
数据结构-元组
查看>>
移动临时表空间
查看>>
chrome允许加载本地文件
查看>>
SocketCluster
查看>>
Tags在XHTML1.0各DTD的校检数据
查看>>
next中layout
查看>>
eclipse 注释字体不一致的问题
查看>>
运放的PID电路
查看>>
Ubuntu下sqlite3的安装及使用
查看>>
LintCode - Backpack
查看>>
使用percona-xtrabackup工具对mysql数据库的备份方案
查看>>
C# URL 中文编码与解码
查看>>
jquery源码解析:pushStack,end,ready,eq详解
查看>>
Qt核心模块的组成
查看>>