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