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 ways to refresh the Android interface, using handler and Postinvalidate () to implement the refresh interface in the thread.
Using handler to refresh the 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 ()//Refresh 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
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 ();
}
}
}