Android 之Handler是如何正确使用
1 public class MainActivity extends BaseActivity { 2 3 //声明 4 private ButtonStateHandler mHandler; 5 6 @Override 7 protected void onCreate(Bundle savedInstanceState) { 8 super.onCreate(savedInstanceState); 9 mBinding = ActivityMainBinding.inflate(getLayoutInflater()); 10 //初始化 11 mHandler = new ButtonStateHandler(new WeakReference<>(this)); 12 setContentView(mBinding.getRoot()); 13 } 14 15 /** 16 * Handler的正确写法 17 */ 18 public static class ButtonStateHandler extends Handler { 19 private WeakReference<MainActivity> mWeakReference; 20 21 public ButtonStateHandler(WeakReference<MainActivity> activity) { 22 this.mWeakReference = activity; 23 } 24 25 @Override 26 public void handleMessage(Message msg) { 27 super.handleMessage(msg); 28 switch (msg.what) { 29 case 1001: 30 mWeakReference.get().mBinding.btnSendOrder.setText((String) msg.obj); 31 break; 32 default: 33 break; 34 } 35 } 36 } 37 38 /** 39 * Handler销毁 40 */ 41 @Override 42 protected void onDestroy() { 43 super.onDestroy(); 44 mHandler.removeCallbacksAndMessages(null); 45 } 46 }