Android Activity runOnUiThread () method, runonuithread

Source: Internet
Author: User

Android Activity runOnUiThread () method, runonuithread
In android, Handler is generally used to communicate with sub-threads.

Now we have a more concise method, namely the runOnUiThread (Runnable) method in the Activity.

 

Use Activity. runOnUiThread (Runnable) to create the updated ui code in Runnable. Then, when you need to update the ui, pass the Runnable object to Activity. runOnUiThread (Runnable ).

The Runnable object can be called in the ui program. If the current thread is a UI thread, the action is immediately executed. If the current thread is not a UI thread, the operation is the UI thread published to the event queue.

 

Package com. app; import android. OS. bundle; import android. support. v7.app. appCompatActivity; import android. widget. toast; public class MainActivity extends AppCompatActivity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // create a Thread new Thread (new Runnable () {@ Override public void run () {// try {Thread with a delay of two seconds. sleep (2000);} catch (InterruptedException e) {e. printStackTrace ();} runOnUiThread (new Runnable () {@ Override public void run () {Toast. makeText (MainActivity. this, "hah", Toast. LENGTH_SHORT ). show ();}});}}). start ();}}

  

RunOnUiThread (Runnable) of the Activity)

    /**     * Runs the specified action on the UI thread. If the current thread is the UI     * thread, then the action is executed immediately. If the current thread is     * not the UI thread, the action is posted to the event queue of the UI thread.     *     * @param action the action to run on the UI thread     */    public final void runOnUiThread(Runnable action) {        if (Thread.currentThread() != mUiThread) {            mHandler.post(action);        } else {            action.run();        }    }

  

 

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.