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