Two ways to refresh the interface in Android

  • 2020-06-12 10:33:17
  • OfStack

Android provides Invalidate methods for interface refreshes, but Invalidate cannot be called directly from within a thread because it violates the single-threaded model: Android UI operations are not thread-safe and must be called within UI threads.

There are two methods of Android interface refresh: Handler and postInvalidate().

Use Handler to refresh the interface

Instantiate 1 Handler object and override handleMessage method to call invalidate() to realize interface refresh; In the thread, the interface update message is sent through sendMessage.


// in onCreate() Open thread in
new Thread(new GameThread()).start(); // instantiation 1 a handler
Handler myHandler = new Handler() {
 // Processing 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 a message
            Activity01.this.myHandler.sendMessage(message);
            try {
             Thread.sleep(100);
            }
            catch (InterruptedException e) {
             Thread.currentThread().interrupt();
            }
  }
 }
}

Use postInvalidate() to refresh the interface

Using postInvalidate is relatively simple. handler is not required, just call postInvalidate directly from 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 You can update the interface directly in a thread
   mGameView.postInvalidate();
  }
 }
}


Related articles: