Android Handler Message Delivery

Source: Internet
Author: User

I. BACKGROUND

For performance tuning purposes, Android UI operations are not thread-safe, which means that if there are multiple threads concurrently manipulating the UI component, it can cause thread safety issues. To solve this problem, Android has a simple principle: only the UI thread (i.e. the main thread) is allowed to modify the UI components in the activity.

When a program starts for the first time, Android initiates a main thread that is primarily responsible for handling UI-related events, such as user key events, User touch screen events, screen drawing events, and distributing related events to the appropriate components for processing. So the main thread is often called the UI thread.

Ii. Two common causes of using handler

1. The UI can only be modified in the main UI. In practice, however, some UI needs to control its modification logic in a child thread, so the child thread needs to modify the UI through the handler notification main thread. This is especially common in game development, such as the need for a newly-started thread to periodically change the UI.

2, in order to avoid the ANR, you should perform long-time operations in the child threads, and after this operation is complete, it is possible to notify the main thread to modify the UI.

III. Basic Principles and procedures

1, the role of handler is mainly 2:

(1) Send a message.

(2) Get and process messages.

2, the basic principle: in order to allow the main thread to deal with the message sent by the child threads in a timely manner, it is obvious that the callback method can only be implemented----developers simply rewrite the methods in the handler class, and when the newly started thread sends a message, the message is sent to the MessageQueue associated with it. The handler will constantly get and process the message from the Messagequere-----which will result in the callback of the method that processes the message in the handler class.

3. The basic steps for using handler in a thread are as follows:

In the called thread, complete the following:

(1) Call Looper's Prepare () method to create a Looper object for the current thread, and when the Looper object is created, its constructor creates a companion MessageQueue.

(2) with Looper, create an instance of the handler subclass and override the Handlermessage () method, which is responsible for handling messages from other threads.

(3) Call Looper's Loop () method to start Looper.

Note: If the called thread is the main thread class, because the system automatically creates an instance of Looper for the main thread, the first to third step can be omitted, and only the 2nd step is required.

Complete in the calling thread:

(1) Create nessage and populate the content.

(2) Use the handler instance created by the called Class to invoke the SendMessage (Message msg) method.

Iv. examples

1. The main thread receives the data and sends it to the child thread to complete some time-consuming operations

Package Com.ljh.handlerdemo1;import Java.util.arraylist;import java.util.list;import android.os.bundle;import Android.os.handler;import Android.os.looper;import Android.os.message;import Android.app.activity;import Android.view.view;import android.widget.edittext;import android.widget.textview;import android.widget.Toast; Public classMainactivity extends Activity {PrivateFinal String Upper_number ="Upper"; PrivateCalthread Calthread; @Overrideprotected voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Calthread=NewCalthread (); Thread T=NewThread (Calthread);    T.start (); }     Public voidcal (View v) {EditText et_digit=(EditText) Findviewbyid (r.id.et_digit); Message msg=NewMessage (); Msg.what=0x1233; Bundle Bundle=NewBundle ();        Bundle.putint (Upper_number, Integer.parseint (Et_digit.gettext (). toString ()));        Msg.setdata (bundle);    CalThread.handler.sendMessage (msg); }    classCalthread implements Runnable { PublicHandler Handler; @Override Public voidrun () {//1. Call Looper's prepare () method to create a Looper object for the current thread, and when the Looper object is created, its constructor creates a companion MessageQueueLooper.prepare (); Handler=NewHandler () {//2. With Looper, create an instance of the handler subclass and override the Handlermessage () method, which is responsible for handling messages from other threads. @Override Public voidhandlemessage (Message msg) {if(Msg.what = =0x1233)                    {                        intUpper =msg.getdata (). GetInt (Upper_number); List<Integer> nums =NewArraylist<integer>(); //calculate all prime numbers starting from 2 to upperouter: for(inti =2; I <= Upper; i++)                        {                            //with I in all numbers starting from 2, to the square root of I                             for(intj =2; J <= Math.sqrt (i); J + +)                            {                                //if it can be divisible, it indicates that the number is not prime                                if(I! =2&& I% J = =0)                                {                                    Continueouter;                        }} nums.add (i); }                        //use Toast to show all the prime numbers that are countedToast.maketext (mainactivity. This, Nums.tostring (), Toast.length_long). Show ();        }            }                                        }; //call Looper's Loop () method to start Looper. Looper.loop (); }}}

Xml:

<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:paddingbottom="@dimen/activity_vertical_margin"Android:paddingleft="@dimen/activity_horizontal_margin"Android:paddingright="@dimen/activity_horizontal_margin"Android:paddingtop="@dimen/activity_vertical_margin"Tools:context=". Mainactivity"> <EditText Android:id="@+id/et_digit"Android:layout_width="wrap_content"Android:layout_height="wrap_content"Android:hint="@string/limit"/> <Button Android:id="@+id/bt_prime"Android:layout_width="wrap_content"Android:layout_height="wrap_content"Android:text="@string/cal"Android:onclick="Cal"Android:layout_below="@id/et_digit"/></relativelayout>

Reference Archive Code HANDLERDEMO1

2, in the main thread, the system has initialized a Looper object, so the program directly create handler can.

Package Org.crazyit.Event; import java.util.timer;import java.util.timertask;import android.app.activity;import Android.os.Bundle;import Android.os.handler;import Android.os.message;import Android.widget.ImageView;/** * Description: * <br/>site: <a href= "http://www.crazyit.org">crazyit.org</a> * <br/>copyright (C), 2001-2014, Yeeku.h.lee * <br/>this program is protected by copyright laws. * <br/>program Name: * <br/>date: * @author Yeeku.h.lee [email protected] * @version 1.0*/ Public classHandlertest extends activity{//defines the ID of a picture that is displayed periodically    int[] Imageids =New int[] {R.drawable.java, r.drawable.ee, R.drawable.ajax, R.drawable.xml, r.drawable    . classic}; intCurrentimageid =0; @Override Public voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.main); Final ImageView Show=(ImageView) Findviewbyid (r.id.show); Final Handler MyHandler=NewHandler () {@Override Public voidhandlemessage (Message msg) {//if the message was sent by this program                if(Msg.what = =0x1233)                {                    //dynamically modify the displayed pictureShow.setimageresource (imageids[currentimageid++%Imageids.length]);        }            }        }; //Define a timer that allows the timer to perform the specified task periodically        NewTimer (). Schedule (NewTimerTask () {@Override Public voidrun () {//send an empty messageMyhandler.sendemptymessage (0x1233); }        }, 0, -); }}

Android Handler Message Delivery

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.