Android notes: the difference and use of invalidate() and postInvalidate()

http://blog.csdn.net/mars2639/article/details/6650876

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. 

invalidate() is used to refresh the View and must be done in the UI thread. For example, when modifying the display of a view, call invalidate() to see the redrawn interface. The call of invalidate() pops the old view from the main UI thread queue. An Android program has only one process by default, but there can be many threads in one process.

Among so many threads, the thread that is mainly responsible for controlling the display, update and control interaction of the UI interface is called the UI thread. Since the onCreate() method is executed by the UI thread, the UI thread can also be understood as the main thread. The remaining threads can be understood as worker threads.

invalidate() has to be mobilized in the UI thread, and the UI thread can be notified to update the interface through the Handler in the worker thread.

And postInvalidate() is called in the worker thread

 

 

Use invalidate() to refresh the interface

  instantiate a Handler object, and rewrite the handleMessage method to call invalidate() to achieve interface refresh; while in the thread, the interface update message is sent through sendMessage. 
// Start the thread in onCreate()

new Thread(new GameThread()).start();

// Instantiate a handler

Handler myHandler = new Handler() { // Process the message after receiving 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 a message
Activity01.this.myHandler.sendMessage(message);
try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } } refresh with postInvalidate() The interface     using postInvalidate is relatively simple, no handler is needed, just call postInvalidate directly in the 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(); } }


























}

Guess you like

Origin blog.csdn.net/kerwinJu/article/details/52885794