There are two sets of methods for implementing view updates in Android, one for invalidate and the other for Postinvalidate, which is used in the UI thread itself and the latter in non-UI threads.
Android provides a invalidate method for interface refreshes, but invalidate cannot be invoked directly on the thread because he violates the Single-threaded model: Android UI operations are not thread-safe and must be invoked in the UI thread.
There are two types of interface refreshes that can be used in the Android program, namely, using Invalidate and using Postinvalidate () to refresh the interface in the thread.
1, using invalidate () Refresh interface
Instantiates a handler object and overrides the Handlemessage method call invalidate () to implement the interface refresh, while the message is updated in the thread through the SendMessage send interface.
Copy Code code as follows:
To open a thread in OnCreate ()
New Thread (New Gamethread ()). Start ();
Instantiate a handler
Handler MyHandler = new Handler () {
Processing after receiving a message
public void Handlemessage (msg) {
Switch (msg.what) {
Case Activity01.refresh:
Mgameview.invalidate (); Refreshing 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, use Postinvalidate () to refresh the interface
The use of postinvalidate is relatively simple, do not need to handler, directly in the thread call Postinvalidate can be.
Copy Code code as follows:
Class Gamethread implements Runnable {
public void Run () {
while (! Thread.CurrentThread (). isinterrupted ()) {
try {
Thread.Sleep (100);
catch (Interruptedexception e) {
Thread.CurrentThread (). interrupt ();
}
Use Postinvalidate to update the interface directly on the thread
Mgameview.postinvalidate ();
}
}
}
The View class Postinvalidate () method source code is as follows, it is also used to handler:
public void Postinvalidate () {
postinvalidatedelayed (0);
}
public void postinvalidatedelayed (long delaymilliseconds) {
We try only with the attachinfo because there ' s No. in invalidating
If we are not attached to our windows
if (mattachinfo!= null) {
Message msg = Message.obtain ();
Msg.what = attachinfo.invalidate_msg;
Msg.obj = this;
MAttachInfo.mHandler.sendMessageDelayed (msg, delaymilliseconds);
}
}
Except that OnCreate () is not running on the UI thread, most of the other methods are running on the UI thread, but as long as you don't have a new thread open, your code basically runs on the UI thread.