处理handler中的内存泄漏

package de.bvb.test;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import java.lang.ref.WeakReference;

public class MainActivity extends Activity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new Thread(new Runnable() {
            @Override
            public void run() {
                //3.子线程中发送消息
                handler.sendEmptyMessage(1);
            }
        }).start();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //4.在onDestroy把消息对象从消息队列移除
        handler.removeCallbacksAndMessages(null);
    }

    //2.创建handler的实例
    private Handler handler = new MyHandler(this);

    //1.创建静态的自定义Handler类
    static class MyHandler extends Handler {
        private WeakReference<Activity> mWeakReference;

        //传入activity,加上弱引用
        public MyHandler(Activity activity) {
            mWeakReference = new WeakReference<>(activity);
        }

        //在handleMessage处理业务
        @Override
        public void handleMessage(Message msg) {
            Activity activity = mWeakReference.get();
            if (activity != null) {
                switch (msg.what) {
                    case 1:
                        break;
                    default:
                        break;
                }
            }
        }
    }
}

 

posted @ 2016-12-16 10:22  MarcoReus  阅读(154)  评论(0编辑  收藏  举报