3.3 A Brief Analysis of Handler Message Passing Mechanism
Category Android Basic Tutorial
Introduction to This Section
In the previous two sections, we studied two event handling mechanisms in Android. Regarding the response to events, there are just these two types; this section will explain to you the information transmission of the Handler in the UI components of the Activity. I believe many friends already know that for thread safety, Android does not allow us to operate the UI outside the UI thread; many times when we refresh the interface, we need to notify the UI components to update through a Handler! In addition to using Handler to complete the interface update, you can also use runOnUiThread() to update, or even more advanced transaction buses, of course, here we only explain the Handler, what is a Handler, the execution process, related methods, and the differences in using Handler in the child thread and the main thread, etc.!
1. Learning Roadmap:
2. Introduction to the Handler Class:
3. Execution Flowchart of Handler:
Flowchart Analysis: Related Terms
>
UI Thread: This is our main thread. When the system creates the UI thread, it initializes a Looper object and also creates a MessageQueue associated with it.
Handler: Its function is to send and handle messages. If you want the Handler to work properly, there must be a Looper object in the current thread.
Message: The message object that the Handler receives and handles.
MessageQueue: The message queue, which manages Messages in a first-in-first-out order. A MessageQueue associated with it is created when the Looper object is initialized.
Looper: Each thread can only have one Looper, which manages the MessageQueue and continuously takes Messages from it and distributes them to the corresponding Handler for processing!
In simpler terms:
>
When our child thread wants to modify the UI components in the Activity, we can create a new Handler object and send messages to the main thread through this object; the messages we send will first wait in the main thread's MessageQueue, and then the Looper will take them out in the order of first in first out, and distribute them to the corresponding Handler for processing according to the what attribute of the message object!
4. Related Methods of Handler:
>
void handleMessage (Message msg): The method for processing messages, usually used to be overridden!
sendEmptyMessage (int what): Send an empty message
sendEmptyMessageDelayed (int what, long delayMillis): Send an empty message after a specified delay of milliseconds
sendMessage (Message msg): Send a message immediately
sendMessageDelayed (Message msg): Send a message after a specified delay of milliseconds
final boolean hasMessage (int what): Check if the message queue contains a message with the what attribute set to the specified value If the parameter is (int what, Object object): In addition to judging the what attribute, it is also necessary to judge whether the Object attribute is the specified object's message
5. Example of Using Handler:
1) Handler Written in the Main Thread
>
In the main thread, since the system has already initialized a Looper object, we can directly create a Handler object to send and process information!
Code Example: A simple program that switches pictures on a timer, using a Timer to periodically modify the content displayed by the ImageView, thus forming a frame animation.
Running Effect Picture:
Implementation Code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
tools:context="com.jay.example.handlerdemo1.MainActivity" >
<ImageView
android:id="@+id/imgchange"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
MainActivity.java:
``` public class MainActivity extends Activity {
// Define the array id for switching pictures
int imgids[] = new int[]{
R.drawable.s_1, R.drawable.s_2,R.drawable.s_3,
R.drawable.s_4,R.drawable.s_5,R.drawable.s_6,
R.drawable.s_7,R.drawable.s_8
{ // Use j to iterate through all numbers starting from 2 up to the square root of i for (int j = 2; j <= Math.sqrt(i); j++) { // If divisible, it indicates that the number is not a prime if (i != 2 && i % j == 0) { continue outer; } } nums.add(i); } // Use Toast to display all the prime numbers counted Toast.makeText(CalPrime.this, nums.toString(), Toast.LENGTH_LONG).show(); } }; Looper.loop(); }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); etNum = (EditText) findViewById(R.id.etNum); calThread = new CalThread(); // Start a new thread calThread.start(); }
// Provide an event handling function for the button's click event public void cal(View source) { // Create a message Message msg = new Message(); msg.what = 0x123; Bundle bundle = new Bundle(); bundle.putInt(UPPER_NUM, Integer.parseInt(etNum.getText().toString())); msg.setData(bundle); // Send a message to the Handler in the new thread calThread.mHandler.sendMessage(msg); } }
PS: This example is from "Android Craziness Lecture Notes"~
Summary of This Section
This section provides a simple analysis of the Handler event passing in Android, clarifying the concepts of Handler, Message, MessageQueue, and Loop, as well as the differences between writing Handlers in the main thread and in a child thread!
1.5.1 Git Tutorial on Basic Operations of Local Repositories
1.8 Project Related Analysis (Various Files, Resource Access)
[2.3.9 RatingBar (Star Rating Bar)](android
A Brief Analysis of Handler Message Passing Mechanism
3.6 Responding to System Setting Events (Configuration Class)
4.4.2 Further Exploration of ContentProvider - Document Provider
5.2.1 Detailed Explanation of Fragment Example - Implementation of Bottom Navigation Bar (Method 1)
5.2.2 Detailed Explanation of Fragment Example - Implementation of Bottom Navigation Bar (Method 2)
5.2.3 Detailed Explanation of Fragment Example - Implementation of Bottom Navigation Bar (Method 3)
5.2.4 Detailed Explanation of Fragment Example - Bottom Navigation Bar + ViewPager Page Switching
6.2 Data Storage and Access - SharedPreferences to Save User Preferences
7.1.1 What to Learn in Android Network Programming and Http Protocol Study
7.1.2 Learning about Android Http Request and Response Headers
[7.5.4 File Download with WebView](android-tutorial
8.3.18 In-depth Explanation of Canvas API (Part 3) Matrix and drawBitmapMesh
8.4.3 Android Animation Collection: Property Animation - First Encounter
8.4.4 Android Animation Collection: Property Animation - Another Encounter
11.0 "The 2015 Latest Android Basic Tutorial" Concludes with Fireworks~
12.2 DrySister Girl Viewing App (First Edition) - 2. Parsing Backend Data
12.4 DrySister Girl Viewing App (First Edition) - 4. Adding Data Caching (Integrating SQLite)