Message mechanisms are mostly used for inter-thread communication and UI update.
Recently, I encountered an application scenario where I needed to update the UI by pressing the button. In this case, you only need to send a message by handler when pressing a key. However, in extreme cases, the keys are pressed too quickly and the UI update is delayed. This will cause message stack and UI update blocking. One solution is to split the key event into onkeydown rather than onkeyup. Send messages in onkeyup, and clear unsent and processed messages in onkeydown. In this way, all the messages processed are sent and processed, and the messages that cannot be processed are cleared. No message stack occurs.
After reading the document, Handler has a method called removeMessages (int) to identify the messages that are not processed. Some people say that removeMessages (0) is to clear all messages, which surprised me.
This document is like this: Remove any pending posts of messages with code 'who' that is in the message queue. the purpose is to Remove all unprocessed messages corresponding to what from the message queue. Note that messages corresponding to what values are not all messages.
Test code: [java]
Private Handler mHandler = new Handler (){
@ Override
Public void handleMessage (Message msg ){
Log. e (msg. what );
}
};
Int count = 0;
@ Override
Public boolean onKeyDown (int keyCode, KeyEvent event ){
Long det = System. currentTimeMillis ()-current;
Current = System. currentTimeMillis ();
Log. I (count );
MHandler. removeMessages (count );
Return super. onKeyDown (keyCode, event );
}
@ Override
Public boolean onKeyUp (int keyCode, KeyEvent event ){
Count ++;
Log. I (count );
MHandler. sendEmptyMessageDelayed (count, 500 );
Return super. onKeyUp (keyCode, event );
}
Private Handler mHandler = new Handler (){
@ Override
Public void handleMessage (Message msg ){
Log. e (msg. what );
}
};
Int count = 0;
@ Override
Public boolean onKeyDown (int keyCode, KeyEvent event ){
Long det = System. currentTimeMillis ()-current;
Current = System. currentTimeMillis ();
Log. I (count );
MHandler. removeMessages (count );
Return super. onKeyDown (keyCode, event );
}
@ Override
Public boolean onKeyUp (int keyCode, KeyEvent event ){
Count ++;
Log. I (count );
MHandler. sendEmptyMessageDelayed (count, 500 );
Return super. onKeyUp (keyCode, event );
} Messages with a latency of 500 ms or less are removed. After changing mHandler. removeMessages (count) to mHandler. removeMessages (0), only messages with the value of what 0 are removed.
From pain, not words, smile and not words