Android notes: differences between invalidate () and postInvalidate () and their usage
Android provides the Invalidate method to refresh the interface, but Invalidate cannot be called directly in the thread, because it violates the single-thread model: Android UI operations are not thread-safe, these operations must be called in the UI thread.
Invalidate () is used to refresh the View and must work in the UI thread. For example, when you modify the display of a view, call invalidate () to view the re-drawing interface. The call of invalidate () is to pop the old view from the main UI thread queue. By default, an Android program has only one process, but a process can have many threads.
In such multithreading, the thread that is mainly responsible for controlling the display, update, and control interaction of the UI interface is called the UI thread, because the onCreate () method is executed by the UI thread, therefore, you can also understand the UI thread as the main thread. Other threads can be understood as worker threads.
Invalidate () must be transferred in the UI thread. In the worker thread, Handler can be used to notify the UI thread to update the interface.
PostInvalidate () is called in the worker thread
Use invalidate () to refresh the interface
Instantiate a Handler object and rewrite the handleMessage method to call invalidate () to refresh the interface. The online program sends the interface to update the message through sendMessage.
// Enable the thread in onCreate ()
New Thread (new GameThread (). start ();,
// Instantiate a handler
Handler myHandler = new Handler (){
// After receiving the message
Public void handleMessage (Message msg ){
Switch (msg. what ){
Case Activity01.REFRESH:
MGameView. invalidate (); // refresh the page
Break;
}
Super. handleMessage (msg );
}
};
Class GameThread implements Runnable {
Public void run (){
While (! Thread. currentThread (). isInterrupted ()){
Message message = new Message ();
Message. what = Activity01.REFRESH;
// Send a message
Activity01.this. myHandler. sendMessage (message );
Try {
Thread. sleep (100 );
} Catch (InterruptedException e ){
Thread. currentThread (). interrupt ();
}
}
}
}
Use postInvalidate () to refresh the page
Using postInvalidate is relatively simple and requires no handler. You can directly call postInvalidate in the thread.
Class GameThread implements Runnable {
Public void run (){
While (! Thread. currentThread (). isInterrupted ()){
Try {
Thread. sleep (100 );
} Catch (InterruptedException e ){
Thread. currentThread (). interrupt ();
}
// Use postInvalidate to directly update the interface in the thread
MGameView. postInvalidate ();
}
}
}