A detailed introduction to Android Handler

  • 2020-05-17 06:33:15
  • OfStack

The definition of Handler
It mainly accepts the data sent by the child thread and updates UI with the main thread.
Explanation: when the application starts, Android will first start a main thread (that is, UI thread), which is the UI control in the administration interface, to distribute events.

For example, if you click on an Button, Android will send an event to Button in response to your action. If a time-consuming operation is required at this point, for example: Networking read data, or read local larger one file, you can't put these actions in the main thread, if you put in the main thread, the interface will appear feign death phenomenon, if 5 seconds is not yet complete, will receive an error message Android system "closed". This time we need to put these time-consuming operation, in the 1 child thread, because the child thread involves UI updates, Android main thread is thread safe, that is to say, updated UI can only in the main thread, it is dangerous to the child thread operation.

This time, Handler came to solve this complex problem, because Handler run in the main thread (UI thread), it has to do with the child thread can be passed through Message object data, this time, Handler will send it to accept the child thread (the child thread sedMessage () method and brother) Message object, (containing data), put the news in the thread queue, cooperate with the main thread in update UI.

Handler1 some characteristics
handler can distribute Message objects and Runnable objects to the main thread, and each instance of Handler will be bound to the thread that created it (1 is usually on the main thread).
It serves two purposes:

1. Schedule the message or Runnable to be executed somewhere on a main thread
2. Schedule an action to be executed in a different thread
Some methods for distributing messages in Handler


post(Runnable)
postAtTime(Runnable,long)
postDelayed(Runnable long)
sendEmptyMessage(int)
sendMessage(Message)
sendMessageAtTime(Message,long)
sendMessageDelayed(Message,long)

The post class method above allows you to arrange an Runnable object into the main thread queue,
The sendMessage class method allows you to queue an Message object with data, waiting for an update.


Handler instance
Subclasses need to inherit the Handler class and override the handleMessage(Message msg) method to accept thread data
The following is an example, which can modify the content of Button via thread


public class MyHandlerActivity extends Activity {
    Button button;
    MyHandler myHandler;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.handlertest);
        button = (Button) findViewById(R.id.button);
        myHandler = new MyHandler();
        //  When creating a 1 A new one Handler When an instance ,  It is bound to the queue of the current thread and message , Start distributing data 
        // Handler It has two functions , (1) :  Regularly perform Message and Runnalbe  object 
        // (2):  let 1 An action , Execute in different threads .
        //  It arranges messages , Use the following methods 
        // post(Runnable)
        // postAtTime(Runnable,long)
        // postDelayed(Runnable,long)
        // sendEmptyMessage(int)
        // sendMessage(Message);
        // sendMessageAtTime(Message,long)
        // sendMessageDelayed(Message,long)

        //  The above methods are as follows:  post The first allows you to deal with it Runnable object 
        //sendMessage() You are allowed to deal with Message object (Message Can contain data ,)
        MyThread m = new MyThread();
        new Thread(m).start();
    }
    /**
    *  Receive a message , Process the message  , this Handler Will be linked to the current main thread 1 Piece of running 
    * */
    class MyHandler extends Handler {
        public MyHandler() {
        }
        public MyHandler(Looper L) {
            super(L);
        }
        //  Subclasses must override this method , Receive data 
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            Log.d("MyHandler", "handleMessage......");
            super.handleMessage(msg);
            //  It can be updated here UI
            Bundle b = msg.getData();
            String color = b.getString("color");
            MyHandlerActivity.this.button.append(color);
        }
    }
    class MyThread implements Runnable {
        public void run() {
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Log.d("thread.......", "mThread........");
            Message msg = new Message();
            Bundle b = new Bundle();//  To store data 
            b.putString("color", " my ");
            msg.setData(b);
            MyHandlerActivity.this.myHandler.sendMessage(msg); //  to Handler Send a message , update UI
        }
    }


Related articles: