Android开发经验谈Android知识

Handler的正确使用姿势

2018-02-05  本文已影响146人  sakura_L

为了避免因为handler持有activity导致的内存泄漏 可以将内部类写成静态内部类

static class myHandler extends Handler {
//弱引用<引用外部类>
WeakReference<Activity> reference;

    myHandler(Activity activity) {
        //构造创建弱引用
        reference = new WeakReference<Activity>(activity);
    }
    @Override
    public void handleMessage(Message msg) {
        //通过弱引用获取外部类.


        Activity activity = reference.get();
        //进行非空再操作
        if (activity != null) {
            switch (msg.what) {
                case 1:
                Log.e("--", "10空");

                //doSomething

                TextView a = activity.getWindow().getDecorView().findViewById(R.id.ida);
                a.setText("this is b");
                Toast.makeText(activity, a.getText(), Toast.LENGTH_LONG).show();
            break;
            }
        }else {
            Log.e("--","2空");

// Toast.makeText(activity.getApplicationContext(),"meile",Toast.LENGTH_LONG).show();
}
}
}

上一篇下一篇

猜你喜欢

热点阅读