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.
AndroidProgramYou can use handler or postinvalidate () to refresh the interface in the process.
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);
- }
- }
Except that oncreate () runs on the UI thread, most of the other methods actually run on the UI thread. In fact, as long as you haven't enabled the new thread, yourCodeIt basically runs on the UI thread.