Android interface refresh

Source: Internet
Author: User

Android interface refresh

There are two interface refresh methods available in the Android program: Invalidate and postInvalidate.

1. Use Handler to refresh the interface:
Invalidate cannot be called directly in the Child thread because it violates the single-threaded model: Android UI operations are not thread-safe and must be called in the UI thread. Instantiate a Handler object and rewrite the handleMessage method to call invalidate () to refresh the interface. In the child thread, send the interface to update the message through sendMessage.

// Enable the Thread new Thread (new GameThread () in onCreate ()). start ();, // instantiate a handlerHandlermyHandler = new Handler () {// After receiving the Message, public void handleMessage (Message msg) {switch (msg. what) {case Activity01.REFRESH: mGameView. invalidate (); // refresh 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 the message Activity01.this. myHandler. sendMessage (message); try {Thread. sleep (100);} catch (InterruptedException e) {Thread. currentThread (). interrupt ();}}}}

2. Use postInvalidate () to refresh the page:
It is relatively simple to use postInvalidate, without handler. You can directly call postInvalidate in the Child thread.

Class GameThread implements Runnable {public void run () {while (! Thread. currentThread (). isInterrupted () {try {Thread. sleep (100);} catch (InterruptedException e) {Thread. currentThread (). interrupt ();} // you can use postInvalidate to directly update the mGameView in the thread. postInvalidate ();}}}



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.