Handler的正确使用姿势

作者: sakura_L | 来源:发表于2018-02-05 16:46 被阅读146次

为了避免因为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();
}
}
}

相关文章

网友评论

    本文标题:Handler的正确使用姿势

    本文链接:https://www.haomeiwen.com/subject/qobdgxtx.html