public abstract class BaseHandler extends Handler {
protected WeakReference<Context> reference;
public BaseHandler(Context context){
reference = new WeakReference<>(context);
}
@Override
public void handleMessage(Message msg) {
if (reference.get()!=null){
handle(msg,reference.get());
}
}
public abstract void handle(Message msg,Object activity);
public void handleDestroy(){
removeCallbacksAndMessages(null);
}
}
使用
public class HandlerActivity extends Activity {
private MyHandler handler = new MyHandler(this);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler.sendEmptyMessage(0);
}
private static class MyHandler extends BaseHandler{
public MyHandler(Context context) {
super(context);
}
@Override
public void handle(Message msg, Object activity) {
Log.e("HandlerActivity",activity.toString());
Toast.makeText((HandlerActivity)activity,"",Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
handler.handleDestroy();
}
}