Handler的正确使用姿势

2018-02-27 11:31:08来源:https://www.jianshu.com/p/b31686175f0e作者: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();
}
}
}








最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台