preface

  • In Android multi-threaded application scenarios, the Handler mechanism is very common

  • Today, I’m going to present a tutorial on how to use the Handler mechanism, which I hope you’ll enjoy

Before reading this article, please read: Android Handler: How the Handler communication mechanism works


directory


Schematic diagram


1. Introduction to the Handler mechanism

  • Define an Android messaging/asynchronous communication mechanism

  • role

In the multi-threaded application scenario, the operation information of UI updating in the worker thread is transferred to the UI main thread, so as to realize UI updating processing by the worker thread and finally realize asynchronous message processing


Schematic diagram

  • Why use itHandlerMessaging mechanism

    A:Multiple threads update the UI concurrently while maintaining thread-safety. Detailed description is as follows


Schematic diagram

  • conclusion

    useHandlerCause: will the worker thread need to operateUIIs passed to the main thread so that the master thread can update as required by the worker threadUI.This avoids the problem of unsafe threading operations

2. Related concepts

The concepts related to the Handler mechanism are as follows:

I’ll use the names Handler, Message, Message Queue, and Looper to familiarize you with the concepts


Schematic diagram


3. Usage

  • HandlerMode of useThe way messages are sent to message queues varies
  • It is divided into two kinds: useHandler. SendMessage (), the use ofHandler. Post ()

4. Procedure

Method 1: Use handler.sendMessage ()

In this way, there are two types: new Handler subclass (inner class), anonymous Handler subclass

But the essence is the same, namely inheriting the Handler class & creating a subclass

/** * Step 1: Create a subclass of Handler (inner class) */ / Custom Handler subclasses (inheriting the Handler class) & Override the handleMessage () method class mHandler extends Handler {// Override handlerMessage() to determine the operation to update the UI @Override public void handleMessage(Message msg) { ... Private Handler mHandler = new mHandler(); private Handler mHandler = new mHandler(); // Step 3: Create the desired Message object Message MSG = message.obtain (); // instantiate the message object msg.what = 1; MSG. Obj = "AA"; // Step 4: Send messages to message queues via Handler in worker Thread // sendMessage ()/POST () // Multithreading can use AsyncTask, inherit Thread class, implement Runnable mHandler.sendMessage(msg); // Step 5: Start the worker Thread (and start Handler) // Multithreading can use AsyncTask, inherit Thread class, implement Runnable /** * mode 2: anonymous inner class */ / Step 1: Private Handler mHandler = new Handler(){// Override public to update the UI by overriding handlerMessage()  void handleMessage(Message msg) { ... // UI operations to perform}}; // Step 2: create the Message object Message MSG = message.obtain (); // instantiate the message object msg.what = 1; MSG. Obj = "AA"; // Multithreading can use AsyncTask, inherit Thread class, implement Runnable mHandler.sendMessage(MSG); // Multithreading can use AsyncTask, inherit Thread class, implement RunnableCopy the code

Approach 2: Use handler.post ()

Private Handler mHandler = new mHandler(); Mhandler. post(new Runnable() {@override public void run() {... mhandler. post(new Runnable() {@override public void run() {... // UI operations to perform}}); // Multithreading can use AsyncTask, inherit Thread class, implement RunnableCopy the code

5. Examples

This article will explain the use of Handler by example

Note:

  1. Due to theHandlerThe role of the =The message that the worker thread needs to manipulate the UI is passed to the main thread, so that the master thread can update the UI according to the needs of the worker thread, thus avoiding unsafe thread operations
  2. So the following example = a simple “update”UIOperation “case
  3. Main layout file same = 1 for displayTextView, as follows:

The layout code: activity_main.xml

<? The XML version = "1.0" encoding = "utf-8"? > <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" tools:context="com.example.carson_ho.handler_learning.MainActivity"> <TextView android:id="@+id/show" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="" /> </RelativeLayout>Copy the code

Carson_Ho Github: Handler; Carson_Ho Github: Handler;

5.1 Using Handler.sendMessage ()

Approach 1: Create a New Handler subclass (inner class)
  • The specific use
public class MainActivity extends AppCompatActivity { public TextView mTextView; public Handler mHandler; // Step 1: Class Mhandler extends Handler {// The handleMessage () method is overridden to determine the operation to update the UI @override public void handleMessage(Message MSG) { Switch (msg.what) {case 1: mtextView.settext (" Thread 1 performed UI operations "); break; Case 2: mtextView.settext (" Perform thread 2 UI operation "); break; } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextView = (TextView) findViewById(R.id.show); // Create Handler instance mHandler = new mHandler (); New Thread() {@override public void run() {try {thread.sleep (3000); } catch (InterruptedException e) { e.printStackTrace(); } // Step 3: create the desired Message object Message MSG = message.obtain (); msg.what = 1; MSG. Obj = "A"; Mhandler. sendMessage(MSG); mhandler. sendMessage(MSG); } }.start(); New Thread() {@override public void run() {try {thread.sleep (6000); } catch (InterruptedException e) { e.printStackTrace(); } // send by sendMessage () // a. Define the Message to sendMessage MSG = message.obtain (); msg.what = 2; MSG. Obj = "B"; B. Send a message to its bound message queue mhandler. sendMessage(MSG); } }.start(); }}Copy the code
  • The results


Schematic diagram

Approach 2: Anonymous inner classes
  • The specific use
public class MainActivity extends AppCompatActivity { public TextView mTextView; public Handler mHandler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextView = (TextView) findViewById(R.id.show); // Step 1: MHandler = new Handler(){// Override public void to update the UI by overriding handlerMessage() HandleMessage (MSG) {switch (msg.what) {case 1: mtextView.settext (" mtextView.settext "); break; Case 2: mtextView.settext (" Perform thread 2 UI operation "); break; }}}; New Thread() {@override public void run() {try {thread.sleep (3000); } catch (InterruptedException e) { e.printStackTrace(); } // Step 3: create the desired Message object Message MSG = message.obtain (); msg.what = 1; MSG. Obj = "A"; Mhandler. sendMessage(MSG); mhandler. sendMessage(MSG); } }.start(); New Thread() {@override public void run() {try {thread.sleep (6000); } catch (InterruptedException e) { e.printStackTrace(); } // send by sendMessage () // a. Define the Message to sendMessage MSG = message.obtain (); msg.what = 2; MSG. Obj = "B"; B. Send a message to its bound message queue mhandler. sendMessage(MSG); } }.start(); }}Copy the code
  • The results


Schematic diagram

5.2 Using handler.post ()

  • The specific use
public class MainActivity extends AppCompatActivity { public TextView mTextView; public Handler mHandler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextView = (TextView) findViewById(R.id.show); // Create Handler instance mHandler = new Handler(); New Thread() {@override public void run() {try {thread.sleep (3000); } catch (InterruptedException e) { e.printStackTrace(); } // send via psot (), Post (new Runnable() {@override public void run() {// Specify the operation UI content Mtextview.settext (" Perform thread 1 UI operation "); }}); } }.start(); New Thread() {@override public void run() {try {thread.sleep (6000); } catch (InterruptedException e) { e.printStackTrace(); } mhandler.post (new Runnable() {@override public void run() {mTextView.settext (" perform thread 2 UI operations "); }}); } }.start(); }}Copy the code
  • The results


    Schematic diagram

This concludes the use of the Handler’s asynchronous messaging mechanism.


6. Summary

  • In this paper,HandlerThe use of asynchronous communication transfer mechanism is fully explained
  • I’m going to go into more detailAndroidIn theHandlerRelated knowledge of asynchronous communication transfer mechanism, such as working mechanism flow, source code analysis, etc., interested in you can continue to pay attention toCarson_Ho android Development Notes

Thumb up, please! Because your encouragement is the biggest power that I write!

The Android event distribution mechanism is the most comprehensive and easy to understand solution for Android screen adaptation. It is the most comprehensive and easy to understand solution for Android screen adaptation. Android development: JSON introduction and the most comprehensive analysis method! BroadcastReceiver Is the most comprehensive version of Android’s BroadcastReceiver


Welcome to attentionCarson_HoJane books!

Share the dry things about Android development from time to time, the pursuit of short, flat, fast, but there is no lack of depth.