Is Handler important in Android? why learn

In Android, the main function of Handler is to realize communication between threads and handle asynchronous tasks. Describe in the simplest words: handler is actually the main thread starting a sub-thread, the sub-thread runs and generates a message, Looper gets the message and passes it to the Handler, and the Handler gets the messages in the sub-thread one by one.

Binder/Socket is used for inter-process communication, while the Handler message mechanism is used for inter-thread communication of the same process. It can be said that as long as there is an asynchronous thread communicating with the main thread, there must be a Handler.

Handler principle

In a multi-threaded application scenario, the operation information that needs to update the UI in the worker thread is transmitted to the UI main thread, so as to realize the update processing of the UI by the worker thread, and finally realize the processing of asynchronous messages.

The main purpose of using the Handler message passing mechanism is to ensure thread safety while multiple threads update the UI concurrently.

Basic usage of Handler

Use Handler in the main thread

Using Handler in the main thread, you can directly use getMainLooper() to get the main thread Looper object and create a Handler instance. For example, update the UI in the child thread in the Activity:

new Thread(new Runnable() {@Overridepublic void run() {// 子线程中进行耗时操作...// 完成后在主线程中更新UImHandler.post(new Runnable() {@Overridepublic void run() {// UI更新代码}});}
}).start();

Use Handler in child thread

To update the UI in the child thread, you need to associate the Looper object of the current thread with the Handler instance so that the message can be executed in the message queue.

new Thread(new Runnable() {@Overridepublic void run() { 在子线程中进行耗时操作...Message message = mHandler.obtainMessage(MSG_ID, arg1, arg2);mHandler.sendMessage(message);}
}).start();mHandler = new Handler(new Handler.Callback() {@Overridepublic boolean handleMessage(Message msg) {switch (msg.what) {case MSG_ID:// UI更新代码return true;default:return false;}}
});

Handler common tasks

3.1 Delayed execution of tasks

Use the Handler.postDelayed() method to delay the message for a period of time before sending it to the message queue. For example:

mHandler.postDelayed(new Runnable() {@Overridepublic void run() {//执行延迟任务}
}, DELAY_MILLIS);

3.2 Periodically execute tasks

Using the combination of Handler.postDelayed() method and Handler.sendMessage() method can implement the function of executing tasks periodically.

mHandler.postDelayed(new Runnable() {@Overridepublic void run() {// 周期性执行任务mHandler.sendMessageDelayed(Message.obtain(mHandler, MSG_ID), INTERVAL);}
}, DELAY_MILLIS);

3.3 Multiple tasks are executed in sequence

Multitasking runs sequentially and serially, and can use message queues to process multiple messages.

mHandler.sendMessage(Message.obtain(mHandler, TASK1_ID, arg1, arg2));
mHandler.sendMessage(Message.obtain(mHandler, TASK2_ID, arg1, arg2));
mHandler.sendMessage(Message.obtain(mHandler, TASK3_ID, arg1, arg2));

Each message is handled individually in the Handler's handleMessage() method.

The similarities and differences of Handler calling methods

Using Handler, there are two ways to add messages to the message queue: post() method and sendMessage() method. The similarities and differences between the two methods are as follows:

4.1 Synchronous and asynchronous methods

  • The post() method is synchronous. That is, after adding a message to the message queue, the message will be processed directly without waiting for the message blocking handler to return.
  • The sendMessage() method is asynchronous. That is, after adding a message to the message queue, the message will not be executed immediately, but will wait for the message blocking handler to return.

4.2 Method parameters

  • The parameter of the post() method is the Runnable object, and the run() method in the Runnable object is the task code to be executed.
  • The parameter of the sendMessage() method is the Message object, and the what field in the Message object is the message ID, and arg1 and arg2 are parameters that can be passed to the handler.

4.3 Delay Time Parameters

  • The postDelayed() method is to put the Runnable object into the message queue and delay the execution for a specified time, and its second parameter is DelayMillis. The post() method does not support a delay time parameter.
  • The sendMessageDelayed() method is to put the Message object into the message queue and delay execution for a specified time, and its second parameter is DelayMillis. The sendMessage() method does not support the delay time parameter.

This article mainly describes the technical importance of Handler in Android development. The technical content of Handler has the following summary↓↓↓: link.juejin.cn/?target=htt…

  1. AsyncTask source code analysis of Handler mechanism
  2. Callable, Future and FutureTask of the Handler mechanism
  3. Handler mechanism
  4. The looper and handle of the Handler mechanism
  5. MessageQueue of Handler mechanism
  6. Message Introduction and Message Object of Handler Mechanism
  7. Native implementation of the Handler mechanism
  8. Thread of Handler mechanism
  9. ThreadLocal of Handler mechanism
  10. Message sending of Handler mechanism
  11. The loop mechanism of the Handler mechanism

final summary

Handler is a core component of the Android system and plays an important role in threading and messaging. It can help users implement message delivery and task execution in different threads, and provides many practical methods.

The most fundamental purpose of using Handler is to solve the problem of multi-threaded concurrency. Android provides us with this mechanism for updating the UI, and we only need to follow this mechanism. There is no need to deal with multi-threading issues anymore. All operations to update the UI are performed in rotation in the message queue of the main thread. It sends the message to the MessageQueue managed by Looper, and is responsible for processing the message distributed to him by Looper.

Guess you like

Origin blog.csdn.net/m0_70748845/article/details/132674269