Android Interface Refresh

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.