Android interface refresh
There are two interface refresh methods available in the Android program: Invalidate and postInvalidate.
1. Use Handler to refresh the interface:
Invalidate cannot be called directly in the Child thread because it violates the single-threaded model: Android UI operations are not thread-safe and must be called in the UI thread. Instantiate a Handler object and rewrite the handleMessage method to call invalidate () to refresh the interface. In the child thread, send the interface to update the message through sendMessage.
// Enable the Thread new Thread (new GameThread () in onCreate ()). start ();, // instantiate a handlerHandlermyHandler = new Handler () {// After receiving the Message, public void handleMessage (Message msg) {switch (msg. what) {case Activity01.REFRESH: mGameView. invalidate (); // refresh the interface break;} super. handleMessage (msg) ;}}; class GameThread implements Runnable {public void run () {while (! Thread. currentThread (). isInterrupted () {Message message = new Message (); message. what = Activity01.REFRESH; // send the message Activity01.this. myHandler. sendMessage (message); try {Thread. sleep (100);} catch (InterruptedException e) {Thread. currentThread (). interrupt ();}}}}
2. Use postInvalidate () to refresh the page:
It is relatively simple to use postInvalidate, without handler. You can directly call postInvalidate in the Child thread.
Class GameThread implements Runnable {public void run () {while (! Thread. currentThread (). isInterrupted () {try {Thread. sleep (100);} catch (InterruptedException e) {Thread. currentThread (). interrupt ();} // you can use postInvalidate to directly update the mGameView in the thread. postInvalidate ();}}}