SoFunction
Updated on 2025-04-11

Several ways to implement interface refresh on Android

Android interface refresh

Android provides the Invalidate method to refresh the interface, but Invalidate cannot be called directly in the thread because it violates the single-threaded model: Android UI operations are not thread-safe, and these operations must be called in the UI thread.

There are two ways to refresh the interface that can be used in Android programs, namely, using Handler and using postInvalidate() to refresh the interface in the thread.

Refresh the interface with Handler

Instantiate a Handler object, and override the handleMessage method to call invalidate() to achieve interface refresh; while sending interface update messages through sendMessage in the thread.


    // Start thread in onCreate()
    new Thread(new GameThread()).start();、

 

    // Instantiate a handler
    Handler myHandler  = new Handler()

    {

       // Process after receiving the message
       public void handleMessage(Message msg)

       {

           switch ()

           {

           case :

              ();    //Refresh the interface
              break;

           }

           (msg);

       }         

    };

 

    class GameThread implements Runnable

    {

       public void run()

       {

           while (!().isInterrupted())

           {

              Message message = new Message();

               = ;

              //Send a message
              (message);

              try

              {

                  (100);

              }

              catch (InterruptedException e)

              {

                  ().interrupt();

              }

           }

       }

    }

Use postInvalidate() to refresh the interface

Using postInvalidate is relatively simple. You don’t need a handler. Just call postInvalidate directly in the thread.

 class GameThread implements Runnable

    {

       public void run()

       {

           while (!().isInterrupted())

           {

              try

              {

                  (100);

              }

              catch (InterruptedException e)

              {

                  ().interrupt();

              }

              //Use postInvalidate to update the interface directly in the thread
              ();

           }

       }

    }

 

refer to:

Android application development reveals

Android Documentation

Thank you for reading, I hope it can help you. Thank you for your support for this site!