解决方法:将handler声明为static静态方法
在activity中:
private final MyHandler handler=new MyHandler(this);//在activity中声明handler
private static class MyHandler extends Handler {
private final WeakReference mActivityReference;
MyHandler(Activity activity) {
this.mActivityReference=new WeakReference<>(activity);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
final MainActivity activity = (MainActivity)mActivityReference.get();//获取弱引用队列中的activity
if(activity!=null){
switch(msg.what) {//获取消息,更新UI
}
}
}
}
//消息队列里面的消息移除
@Override
protected voidonDestroy() {
super.onDestroy();
_handler.removeCallbacksAndMessages(null);
context=null;
}
在fragment中
private final MyHandler handler=new MyHandler(this);//在activity中声明handler
private static class MyHandler extends Handler {
private final WeakReference mFragmentReference;
MyHandler(Fragment fragment) {
this.mFragmentReference=new WeakReference<>(fragment);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
final MainFragment fragment= (MainFragment)mFragmentReference.get();
if(fragment!=null){
switch(msg.what) {//获取消息,更新UI
}
}
}
}
//消息队列里面的消息移除
@Override
protected voidonDestroy() {
super.onDestroy();
_handler.removeCallbacksAndMessages(null);
}
网友评论