Two ways to refresh the interface in Android _android

Source: Internet
Author: User

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 ();
}
}
}

Related Article

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.