There are two sets of methods to update the view in Android: invalidate and postinvalidate. The former is used in the UI thread itself, the latter is used in non-UI threads.
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.
There are two interface refresh methods that can be used in Android programs: handler and postinvalidate.
1. 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 ();
}
}
}
}
2. 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 ();
}
}
}
In the View class, the source code of the postinvalidate () method is as follows. It can be seen that handler is also used:
- Public void postinvalidate (){
- Postinvalidatedelayed (0 );
- }
- Public void postinvalidatedelayed (long delaymilliseconds ){
- // We try only with the attachinfo because there's no point in invalidating
- // If we are not attached to our window
- If (mattachinfo! = NULL ){
- Message MSG = message. Obtain ();
- MSG. What = attachinfo. invalidate_msg;
- MSG. OBJ = this;
- Mattachinfo. mhandler. sendmessagedelayed (MSG, delaymilliseconds );
- }
- }