Android Learning Summary ———— the use of Handler

Source: Internet
Author: User

First, the basic concept

Handler popular point is the processing object used to send data between various threads. In any thread, the data can be sent to that thread by means of the Handler.sendmessage (message) method, as long as the handler of another thread is obtained. Based on this mechanism, we can create a new thread when dealing with multithreading, which has a handler in the UI thread. When thread finishes processing some time-consuming operations, it sends data to the UI thread by passing the handler, and the UI thread updates the interface.

Main thread: Runs all UI components that complete this task through a message queue. The device translates each user's actions into messages and puts them in a running message queue. The main thread is in a loop and processes each message. If any one message takes more than 5 seconds, Android will throw the ANR. So a task takes more than 5 seconds, it should be done in a separate thread, or deferred, when the main thread is idle and then returned to handle it.

Second, the introduction of handler class

(Image source: http://www.runoob.com/w3cnote/android-tutorial-handler-message.html)

  

Third, the implementation flowchart of Handler

(Image source: http://www.runoob.com/w3cnote/android-tutorial-handler-message.html)

  

  Flowchart Analysis: related nouns

    • UI Thread : is our main thread, the system initializes a Looper object when creating the UI thread, and also creates a MessageQueue associated with it;
    • Handler: The function is to send and process information, if you want Handler to work properly, there is a Looper object in the current thread
    • Message: Handler received and processed messages object
    • MessageQueue: Message Queuing, FIFO management message, which creates a MessageQueue associated with the Looper object when it is initialized;
    • Looper: Each thread can only have one Looper, manage MessageQueue, and constantly remove the message from it to the corresponding handler processing!
Iv. Sample Code

  4.1Handler written in the main thread

  In the main thread, because the system has initialized a Looper object, so we directly create the handler object, you can send and process information! The layout code looks like this:

<?xml version= "1.0" encoding= "Utf-8"?><relativelayout    xmlns:android= "http// Schemas.android.com/apk/res/android "    android:layout_width=" Match_parent "    android:layout_ Height= "match_parent"    android:gravity= "center" >    <ImageView        Android:id = "@+id/imgchange"        android:layout_width= "Wrap_content"        android:layout_height = "Wrap_content"        android:layout_alignparentleft= "true"        android:layout_ Alignparenttop= "true"/></relativelayout>

The Mainactivity.java code looks like this:

 Packagecom.nyl.handlertest;Importandroid.app.Activity;ImportAndroid.os.Handler;ImportAndroid.os.Message;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.os.Bundle;ImportAndroid.widget.ImageView;ImportJava.util.Timer;ImportJava.util.TimerTask; Public classMainactivityextendsActivity {PrivateImageView Imgchange; //defines the array ID of the switched picture    intImgids[] =New int[]{r.mipmap.ic_launcher,r.mipmap.h,r.mipmap.h1, R.mipmap.h2,r.mipmap.h3,r.mipmap.h4,    R.MIPMAP.H5,R.MIPMAP.H6}; intImgstart = 0; FinalHandler Handler =NewHandler () {/*** Override the Handlemessage method to determine if follow-up is performed based on what value in MSG *@parammsg*/@Override Public voidhandlemessage (Message msg) {if(Msg.what = = 0x123) {Imgchange.setimageresource (Imgids[imgstart+ +% 8]);    }        }    }; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Imgchange=(ImageView) Findviewbyid (R.id.imgchange); //using timers, let handler send an empty message every 200 milliseconds        NewTimer (). Schedule (NewTimerTask () {@Override Public voidrun () {Handler.sendemptymessage (0x123); }        },0,200); }}

When we run the program, will jump every 2 seconds to the next picture, (because it is not dynamic to show you the effect) or to do it yourself!

4.2 Handler written in a child thread

  If handler is written in a sub-thread, we need to create a Looper object ourselves! The process is created as follows:

    1. The Looper.prepare () method is called directly to create a Looper object for the current thread, and its constructor creates a matching MessageQueue;
    2. Create a handler object and override the Handlemessage () method to handle information from other threads!
    3. Call the Looper.loop () method to start the Looper

Enter a number that calculates all the prime numbers in this range after the toast is output, as shown in the following layout:

<?xml version= "1.0" encoding= "Utf-8"?><LinearLayout xmlns:android= "Http://schemas.android.com/apk/res/android"Android:id= "@+id/activity_main"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "Vertical" > <EditText Android:id= "@+id/etnum"Android:inputtype= "Number"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:hint= "Please enter the upper limit"/> <Button android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:onclick= "Cal"Android:text= "Calculation"/></linearlayout>

The key code is as follows:

 PackageCom.nyl.handlerdemo;Importandroid.app.Activity;ImportAndroid.os.Handler;ImportAndroid.os.Looper;ImportAndroid.os.Message;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.widget.EditText;ImportAndroid.widget.Toast;Importjava.util.ArrayList;Importjava.util.List; Public classMainactivityextendsActivity {Private StaticString upper_num = "UPPER"; PrivateEditText Etnum;    Calthread Calthread; //define a thread class    classCalthreadextendsthread{ PublicHandler Handler;  Public voidrun () {looper.prepare (); Handler=NewHandler () {//define methods for handling messages@Override Public voidhandlemessage (Message msg) {if(Msg.what = = 0x123){                        intUpper =msg.getdata (). GetInt (Upper_num); List<Integer> nums =NewArraylist<>(); //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 ();            }                }            };        Looper.loop (); }} @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Etnum=(EditText) Findviewbyid (r.id.etnum); Calthread=NewCalthread (); //start a new threadCalthread.start (); }    //provides event handlers for button click events     Public voidcal (View source) {//Create a messageMessage message =NewMessage (); Message.what= 0x123; Bundle Bundle=NewBundle ();        Bundle.putint (Upper_num,integer.parseint (Etnum.gettext (). toString ()));        Message.setdata (bundle); //send a message to a handler in a new threadcalThread.handler.sendMessage (message); }}

When you enter a number and click the Calculate button, the effect is as follows:

  

Ok,handler the use of our temporary learning here, there is no shortage of places to welcome friends to provide valuable advice!

Android Learning Summary ———— the use of Handler

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.