Piglet's Android starter Road Day 4-part 3

Source: Internet
Author: User

Piglet's Android starter Road Day 4-part 3

--handler message passing mechanism of Android event processing mechanism

------------ Reprint Please specify the source--coder-pig



Introduction to this section:

In the previous two sections, we have learned more about two kinds of event handling mechanisms: Listening and callback.

Seemingly completed the Android event processing mechanism, in fact, these two just happened to touch ah and the like to make the incident response;

And today this part is about modifying the UI component in the activity, some information is passed; I believe we all know that we can only

In the main thread to modify the UI components in the activity, but we need to periodically modify the UI components in a custom thread to

Value, we cannot modify the value of the UI component directly in the custom thread, so we can only send information to notify the main thread to update the UI component;

And this message of the east is what we are going to talk about today handler!



Learning Roadmap for this section




Body:


introduction of the handler class:



handler diagram of the execution process:



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 message 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 take out the message to the corresponding handler processing!


To put it simply:

When our child thread wants to modify the UI component in the activity, we can create a new handler object to send the message to the main thread through this object;

The information we send will be MessageQueue to the main thread, which is taken out in first-in, first-out order, and then based on the message object's

What attributes are distributed to the corresponding handler for processing!




related methods of handler:

void Handlemessage (Message msg) : The method of handling messages, usually used to be overridden!

sendemptymessage (int what) : Send an empty message

sendemptymessagedelayed (int what,long delaymillis) : Specifies how many milliseconds to delay sending empty information

sendMessage (Message msg) : Send Message now

sendmessagedealayeddelayed (Message msg) : Specify how many milliseconds to delay sending information

Final Boolean hasmessage (int what) : Checks whether Message Queuing contains a message with the What property is the specified value

if the parameter is (int what,object Object) : In addition to judging the What property, you also need to determine whether the object property is a message for the specified objects



examples of use of handler:

The use of handler is divided into the following two scenarios:


①handler 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!


code example:

A simple program to switch pictures regularly, through timer timer, modify the content of ImageView display, thus forming the animation

Main.xml

<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

Package Com.jay.example.handlerdemo1;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; public class Mainactivity extends Activity {//defines an array of switched pictures idint 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};int Imgstart = 0;@ overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); final ImageView Imgchange = (ImageView) Findviewbyid (R.id.imgchange); final Handler MyHandler = New Handler () {@Override//Overrides the Handlemessage method, depending on what value in MSG determines whether to perform subsequent operations public void Handlemessage (Message msg) {if ( Msg.what = = 0x123) {imgchange.setimageresource (imgids[imgstart++% 8]);}}};/ /using timers, let handler send an empty message every 200 milliseconds to the new Timer (). Schedule (new TimerTask () {@Overridepublic void run () { Myhandler.sendemptymessage (0x123);}}, 0,200);}} 


Run:




②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) Call the Looper.prepare () method directly to create a Looper object for the current thread, and its constructor creates the 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


PS: There is no good example here, the author level is limited,

Only direct copy of Li Gang's crazy handout in the code, the code function is to enter a number, and finally through

Toast outputs all prime numbers within this range!


code example:

Main.xml

<linearlayoutxmlns:android= "Http://schemas.android.com/apk/res/android" 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"/><buttonandroid:layout_width= "match_parent" android:layout_height= "Wrap_content" Android:o Nclick= "cal" android:text= "calculation"/></linearlayout>

Mainactivity.java:

Package Org.crazyit.handler;import Java.util.arraylist;import Java.util.list;import android.app.activity;import Android.os.bundle;import Android.os.handler;import Android.os.looper;import Android.os.message;import Android.view.view;import Android.widget.edittext;import Android.widget.toast;public class CalPrime extends Activity{ Static final String Upper_num = "UPPER"; EditText Etnum; Calthread calthread;//defines a thread class Calthread extends Thread{public Handler mhandler;public void Run () {Looper.prepare () ; mhandler = new Handler () {//define method for handling messages @overridepublic void Handlemessage (Message msg) {if (Msg.what = 0x123) {int upper = ms G.getdata (). GetInt (Upper_num); list<integer> nums = new arraylist<integer> ();//Calculates all prime numbers starting from 2 to upper outer:for (int i = 2; i <= upper; i++) {//With I at 2 starting, to the square root of I for all numbers for (int j = 2; J <= Math.sqrt (i); + j) {//if divisible, indicating that this number is not prime if (I! = 2 && I% J = = 0) {Co Ntinue outer;}} Nums.add (i);} Use Toast to show all prime number Toast.maketext (Calprime.this, nums.tostring (), ToaSt. Length_long). Show ();}}; Looper.loop ();}} @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.main); etnum = (EditText) Findviewbyid (r.id.etnum); calthread = new Calthread ();//Start new thread Calthread.start ();} Provides event handlers for button click events public void Cal (View source) {//create message msg = new Message (); msg.what = 0x123; Bundle bundle = new bundle (); Bundle.putint (Upper_num, Integer.parseint (Etnum.gettext (). toString ())); Msg.setdata ( bundle);//Send Message CalThread.mHandler.sendMessage (msg) to the handler in the new Thread;}}


Use of the process has been said, we look at the code experience it!

When there are good examples, I will turn around and change!



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.