There are two kinds of interface refresh methods that can be used in Android programs , namely, using Invalidate and using Postinvalidate () to refresh the interface in thread.
1. Refresh the interface with handler:
Invalidate cannot be called directly in a child thread because he is violating the single-threaded model: Android UI operations are not thread-safe, and these operations must be called in the UI thread. Instantiate a handler object and override the Handlemessage method call invalidate () to implement the interface refresh, and update the message through the SendMessage send interface in the child thread.
To open a thread in OnCreate ()
New Thread (New Gamethread ()). Start ();
Instantiate a handler
Handler
MyHandler
= new Handler ()
{
Receive Message post processing
public voidHandlemessage(Message 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 Message
Activity01.this.myHandler.sendMessage (message);
Try
{
Thread.Sleep (100);
}
catch (Interruptedexception e)
{
Thread.CurrentThread (). interrupt ();
}
}
}
}
2. Use Postinvalidate () to refresh the interface:
Using Postinvalidate is simpler and requires no handler to invoke postinvalidate directly in a child thread.
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 in the thread
mgameview.postinvalidate ();
}
}
}
Android Interface Refresh