Update view differences between Invalidate and postInvalidate in android

  • 2020-05-09 19:14:11
  • OfStack

There are two sets of methods to implement view updates in Android, one is invalidate, the other is postInvalidate, where the former is used in the UI thread itself, and the latter is used in non-UI threads.

Android provides the Invalidate method for interface refresh, but Invalidate cannot be called directly from a thread because it violates the single-threaded model: Android UI operations are not thread-safe, and they must be called from an UI thread.

There are two interface refresh methods available in Android programs, invalidate and postInvalidate() to refresh the interface in threads.

1. Refresh the interface with invalidate()
Instantiate an Handler object, rewrite the handleMessage method, and call invalidate() to refresh the interface. In the thread, the interface update message is sent through sendMessage.
 
//  in onCreate() Middle start thread  
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(); 
} 
} 
} 
} 

2. Refresh the interface using postInvalidate()
postInvalidate is easier to use. Instead of handler, you can call postInvalidate directly from a 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(); 
} 
} 
} 
View  In the class postInvalidate() Method source code as follows, you can see it is also used handler :  
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() doesn't run on the UI thread, most of the other methods run on the UI thread, and as long as you don't start a new thread, your code will basically run on the UI thread.

Related articles: