• Android中使用Handler造成内存泄露的分析和解决


    Handler 内部类持有 外部类Activity的引用,假设Activity退出而Handler还有延迟处理的消息没有处理完,会导致Activity不能回收。重复如此会导致内存泄露。

    解决方式一: onDestroy时清除消息,mHandler.removeCallbacksAndMessages(null); // 參数为null时会清除全部消息。

    解决方式二:声明Handler为static并持有Activity的弱引用。关键看程序中凝视的地方

    public class MainActivity extends Activity {
    
        private static final String tag = "MainActivity";
    
        private TextView mTvShow;
    
        private MyHandler mHandler;
    
        private static final int DELAY_TIME = 10000; // set to 5s and 10s to check result.
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            mHandler = new MyHandler(MainActivity.this);
    
            Log.e(tag, "onCreate");
    
            mTvShow = (TextView)findViewById(R.id.tv_show);
    
            new Thread() {
                @Override
                public void run() {
    
                    mHandler.sendEmptyMessageDelayed(1, DELAY_TIME);
                    Log.e(tag, "msg send");
                }
            }.start();
    
        }
    
        @Override
        protected void onDestroy() {
            Log.e(tag, "onDestroy");
            super.onDestroy();
        }
    
        static class MyHandler extends Handler{
    
            WeakReference<MainActivity> mWeakActivity;
    
            public MyHandler(MainActivity activity) {
                mWeakActivity = new WeakReference<>(activity);
            }
    
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
    
                MainActivity activity = mWeakActivity.get();
    
                Log.e(tag, "handleMessage," + msg.what);
                // 5s is not null, 10s is null, tell that activity is recycled.
                if(null == activity){
                    Log.e(tag, "null");
                }else{
                    Log.e(tag, "not null");
                    activity.mTvShow.setText("delay show");
                }
            }
        }
    }
    



  • 相关阅读:
    阿里MaxCompute(原ODPS)如何修改列字段数据类型
    解决SQL语句在Dapper执行超时比Query慢的问题
    IIS部署FLASK网站
    如何在vscode中调试python scrapy爬虫
    [转]阿拉伯数字转一二三和壹贰叁
    第三册复习
    不知道的口语
    跟小丸子学基础口语21-25
    跟小丸子学基础口语16-20
    跟小丸子学基础口语11-15
  • 原文地址:https://www.cnblogs.com/brucemengbm/p/6718322.html
Copyright © 2020-2023  润新知