在android中经常会使用到Handler来进行一些线程之间的操作,使用非常普及,普通用法如下:
private Handler mHandler = new Handler(){
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
method();
break;
default:
break;
}
};
};}
升级版用法如下:
private MainActivityHandler mHandler = new MainActivityHandler(this);
private static class MainActivityHandler extends Handler{//内部类
private WeakReference<MainActivity> refer;
public MainActivityHandler(MainActivity activity ){
refer = new WeakReference<MainActivity>(activity);
}
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
MainActivity activity = refer.get();
if(activity == null)return;
switch (msg.what) {
case 1:
method();
break;
default:
break;
}
super.handleMessage(msg);
}
}
在activity或者fragment的onDestroy方法中需要移除掉Handler
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
if(mHandler != null){
mHandler.removeCallbacksAndMessages(null);
}
super.onDestroy();
}