Android Studio for Android Learning (19) Latest Handler message delivery mechanism full solution

Source: Internet
Author: User

1.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 is launched for the first time, Android initiates a primary 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. handler The meaning of existence is a message mechanism that can be created in one thread and triggered in another threadThe role of 2.Handler:
    • (1) Send a message in a thread.
    • (2) Gets and processes the message in another thread.
The 3.Handler class contains the following methods for sending and processing messages (only the common ones are listed here, and more can be found on their own):
    • ? void Handlermessage (Message msg): The method that processes the message, which is typically used to be overridden.
    • ? Final Boolean hasmessage (int): Checks whether Message Queuing contains a message with the What property is the specified value.
    • ? Sendemptymessage (int): Send an empty message
    • ? Final Boolean sendMessage (Message msg): Sends a message immediately, paying attention to this return value, and returns True if the message was successfully placed inside the message queue, and vice versa, returns false;
4. Complete the following in the called Thread: (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 a message and populate the content. (2) Use the handler instance created by the called Class to invoke the SendMessage (Message msg) method. 5. The following example is handler in the main thread, processing the message, sending a message in the child thread, this example handler written in the main thread. Main.xml
<?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: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="Com.dragon.testfuction.Main">    <ImageViewandroid:id= "@+id/show"android:layout_width="Wrap_ Content "android:layout_height=" wrap_content " />                        </relativelayout>
Main.java
 PackageCom.dragon.testfuction;ImportAndroid.os.Handler;ImportAndroid.os.Message;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.widget.ImageView;ImportAndroid.widget.Toast;ImportJava.util.Timer;ImportJava.util.TimerTask; Public  class Main extends appcompatactivity {//define picture Display ID    int[] Imageids =New int[]{R.drawable.one, R.drawable.two, R.drawable.three, r.drawable.four};intCurrentimageid =0;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.main);FinalImageView show = (ImageView) Findviewbyid (r.id.show);FinalHandler MyHandler =NewHandler () {@Override             Public void  Handlemessage(Message msg) {//Check the source of the message sent, if it is sent by this program                if(Msg.what = =0x1233){//Dynamic modification of picturesShow.setimageresource (Imageids[currentimageid++%imageids.length]); }            }        };//Define a timer to perform the specified tasks periodically        NewTimer (). Schedule (NewTimerTask () {@Override             Public void Run(){//Gets the handle object created in the parent thread in the child thread, which is used to send a message to the parent thread's message queue (in this way, the UI thread updates the interface with the main thread in other sub-threads)Myhandler.sendemptymessage (0x1233); }    },0, -);}}
6. To avoid the ANR, longer-time operations should be performed in child threads, you may need to notify the main thread to modify the UI after this operation is complete. notifies the main thread of an example of modifying a UI component after performing a time-consuming task in a child thread: Computes a prime number with a new process, and uses a toast to show the example is to send a message in the main thread, fetch it in a child, and process the message (examples from the crazy Java handout), this example handle written in a child thread. Main.xml
<?xml version= "1.0" encoding= "Utf-8"?><linearlayout 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:orientation="Vertical"  Tools:context="Com.dragon.testfuction.Main">                        <edittext  android:id  = "@+id/etnum"  android:inputtype  =< Span class= "Hljs-value" > "number"  android:layout_width  =" wrap_content " android:layout_height  =" wrap_content " android:hint  =" Please input upper number "/>     <buttonandroid:layout_width="Match_parent"android:layout_height= "Wrap_content" Android:onclick="cal"android:text="Calculate"/>                                </linearlayout>
Main.java
 PackageCom.dragon.testfuction;ImportAndroid.os.Handler;ImportAndroid.os.Looper;ImportAndroid.os.Message;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.widget.EditText;ImportAndroid.widget.Toast;ImportJava.util.ArrayList;ImportJava.util.List; Public  class Main extends appcompatactivity {    Static FinalString Upper_num ="Upper";    EditText Etnum; Calthread Calthread;//define a thread classClass Calthread extends Thread { PublicHandler Mhandler; Public void Run(){//Create Looper object, each thread must have a Looper object using handleLooper.prepare ();//Sub-thread definition handler get processing messageMhandler =NewHandler () {//define methods for handling information                    @Override                     Public void Handlemessage(Message msg) {if(Msg.what = =0x123){intUpper = Msg.getdata (). GetInt (Upper_num); List<integer> nums =NewArraylist<integer> (); Outer//Prime number is also prime, except 1 and itself, cannot be divisible by other                                 for(inti =2; I <=upper;i++) { for(intj=2; j<= math.sqrt (i); j + +) {//If it can be divisible, the description is not prime                                        if(i!=2&& i%j==0){ContinueOuter                                }} nums.add (i); }//Toast to show all the counted prime numbersToast.maketext (Main. This, Nums.tostring (), Toast.length_long). Show ();                }                    }                }; Looper.loop ();//Start Looper}    }@Override     Public void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.main);        Etnum = (EditText) Findviewbyid (r.id.etnum); Calthread =NewCalthread (); Calthread.start ();//Start new thread}//button event Click handler function     Public void Cal(View Source) {//Create messageMessage msg =NewMessage (); Msg.what =0x123; Bundle bundle =NewBundle ();        Bundle.putint (Upper_num,integer.parseint (Etnum.gettext (). toString ())); Msg.setdata (bundle);//In the main thread, want to send a message to the handler in the new threadsCalThread.mHandler.sendMessage (msg);//Send a message in the main thread}}
7. Summary:

8. Note
    • 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 message objects
    • 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!
Looper.prepare provides the following source code:
  /** Initialize The current thread as a looper. * This gives you a chance to create handlers so reference * This looper, before actually starting the loop.      Be sure to call * {@link #loop ()} After calling this method, and end it by calling * {@link #quit ()}. */     Public Static void Prepare() {Prepare (true); }Private Static void Prepare(Booleanquitallowed) {if(Sthreadlocal.get ()! =NULL) {Throw NewRuntimeException ("One Looper may be created per thread"); } sthreadlocal.set (NewLooper (quitallowed)); }
9. According to the above two examples, we are careful to distinguish Main ThreadNeutralization Child ThreadsIn the difference, if you have questions welcome message, and also engaged in AR native development can join the following groups or attention to the public number ar Guide

Reference:

1.http://www.runoob.com/w3cnote/android-tutorial-handler-message.html
2.http://www.nljb.net/default/android%e4%b9%8bhandler%e6%b6%88%e6%81%af%e4%bc%a0%e9%80%92%e6%9c%ba%e5%88%b6%e4 %bd%bf%e7%94%a8/
3.http://www.itmmd.com/201502/575.html
4.http://www.kancloud.cn/digest/tttkkk/125281

Android Studio for Android Learning (19) Latest Handler message delivery mechanism full solution

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.