View. post(Runnable action)

Update the UI in the child thread

   textView.post(new Runnable() {
        @Override
        public void run() {
            textView.setText("Update textView"); }});Copy the code

You can use this method to update a view if it is available in your child thread. The view also has a method view.postDelayed(Runnable action, long delayMillis) which is used to delay the delivery.

RunOnUiThread (Runnable action)##

If the method is in a child thread, note that the context object is the MainActivity in the main thread.

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //At this point in the main thread, update UI}});Copy the code

Method 3: Handler mechanism

Handler mainHandler = new Handler(); Handler mainHandler = new Handler(looper.getMainLooper ())) Handler mainHandler = new Handler(looper.getMainLooper ()) Handler. Post (Runnable R) puts message processing on the main thread message Queue to which this Handler is attached. (1) Suppose the method is in a child thread

 Handler mainHandler = new Handler(Looper.getMainLooper());
    mainHandler.post(new Runnable() {
        @Override
        public void run() {
            //In the main thread, update UI}});Copy the code

1. PostAtTime (Runnable r, long uptimeMillis); 2. 2. PostAtDelayed (Runnable r, long delayMillis); // Delay delayMillis milliseconds before sending a message (2) : suppose it is in the main thread

Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch(msg.what) {
                case 0:
                    //Update the UI etc.break;
                default:
                    break; }}}Copy the code

MainHandler can then be passed between classes as a parameter, and when the UI needs to be updated, sendMessage can be called to perform operations in handleMessage. The child thread sends a message to the main thread to update the UI

/** * get messages using obtainMessage() as much as possible. MSG =new Messenger(); * As to why this method still exists, it is probably necessary to exist. (Reserved for further study) */ new Thread(new Runnable(){ @Override public void run() { // Time-consuming operation. After completion, a message is sent to Handler to complete UI update. mHandler.sendEmptyMessage(0); // To pass data, use the following method; Message msg =new Message(); MSG. Obj = "data "; // Can be a basic type, can be an object, can be a List, map, etc.; mHandler.sendMessage(msg); myHandler.sendEmptyMessage(0); /EndEmptyMessageAtTime (int what, long uptimeMillis); /SendEmptyMessageDelayed (int what, long delayMillis); // Delay sending empty Message sendMessageAtTime(Message MSG, long uptimeMillis); /SendMessageDelayed (Message MSG, long delayMillis); // delay sending messages sendMessageAtFrontOfQueue (Message MSG); /}}).start();Copy the code

Method 4 AsyncTask