handler removeMessages()的烏龍

1.最近開發自定義鍵盤時,發現一個烏龍,是通過handler發送循環消息,然後切換鍵盤的時候remove掉循環消息,發現remove不掉,調試半天才突然想起來是在handleMessage中remove的,引起此現象的代碼如下:

	      Handler mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    switch (msg.what) {
                        case MSG_REPEAT:
                            if (repeatKey()) {
                                Message repeat = Message.obtain(this, MSG_REPEAT);
                                sendMessageDelayed(repeat, REPEAT_INTERVAL);
                            }
                            break;
                   
                    }
                }
            };
       
      private boolean repeatKey() {
     .....
           // 在此方法中通過種種回調,最終調用了去MSG_REPEAT的方法:
              mHandler.removeMessages(MSG_REPEAT);
        return true;
    }

這種方式是去不掉what=MSG_REPEAT的消息的,導致了死循環,需要再發一個handler的消息
調用.removeMessages(MSG_REPEAT);
結論就是不能再handleMessage中remove當前的消息,因爲此時MessageQueue還不存在what=MSG_REPEAT的Message對象

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章