In Android we generally use Handler to do the communication between the main thread and the child thread.
Now there is a more concise way of writing, which is the Runonuithread (Runnable) method in Activity.
Use Activity.runonuithread (Runnable) to create the code that updates the UI in Runnable, and then pass the Runnable object to Activity.runonuithread when the UI needs to be updated ( Runnable).
runnable can be called in the UI program. If the current thread is the UI thread, then the action is performed immediately. If the current thread is not a UI thread, the action is the UI thread that is 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 for new thread (new Runnable () { @Override public void Run () { //Delay two second try { Thread.Sleep (a); } catch (Interruptedexception e) { e.printstacktrace (); } Runonuithread (New Runnable () { @Override public void Run () { toast.maketext (mainactivity.this, "hah", Toast.length_short). Show ();}) ;} ). Start (); }}
Activity's Runonuithread (Runnable)
/** * Runs The specified action on the UI thread. If the current thread was the UI * thread, then the action is executed immediately. If the current thread was * not the UI thread, the action was 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 ();} }
The Android Activity Runonuithread () method uses