The learning Path of Android development--the first experience of asynchronous message Handler,message,looper and Asynctask

Source: Internet
Author: User

In the easy music player. used the handler. Also not too much to study, here to learn the next Android under the asynchronous message processing mechanism.

The handler used here is mainly in the thread can not update the UI, and need to pass handler talent enough. There are several concepts about asynchronous message processing.

1. Message: Messages, data units for inter-thread communication.

For example, to download a song in the background and download it. To update the UI, you can send a message that includes the update information to the UI thread.

2, MessageQueue: Message queue. Used to store all messages published through Handler, due to the queue. So it's first-out.

3, the main processor of Handler:message. is responsible for adding messages to the message queue and for processing messages in the message queue.

4, Looper: Circular management MessageQueue. Loops out the message in the MessageQueue. and handed over to the corresponding handler for processing.

5, Thread: UI thread is the main thread,android startup program will create a MessageQueue for him.

Each thread can contain a Looper object and a MessageQueue data structure.

Here's a sample, or a new projecthandlertest. Write a simple layout such as the following:

<?

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 "android:layout_margin=" 10DP "tools:context=" com.example.jared.handlertest . Mainactivity "> <edittext android:id=" @+id/inputcontent "android:layout_width=" Match_parent " android:layout_height= "Wrap_content" android:hint= "Enter what you want to change"/> <button android:id= "@+id/changeviewc Ontent "android:layout_width=" match_parent "android:layout_height=" wrap_content "android:text=" change The ViewContent "android:textallcaps=" false "/> <textview android:id=" @+id/testhandler "Android oid:text= "I am old!!!" Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:layout_margin= "20DP" Android:textsize= "22dip" android:layout_gravity= "center"/></linearlayout>


Enter the content here. Press button to change the contents of the TextView. Write mainactivity code such as the following:

Package Com.example.jared.handlertest;import Android.os.handler;import Android.os.message;import Android.support.v7.app.appcompatactivity;import Android.os.bundle;import Android.view.view;import Android.widget.button;import Android.widget.edittext;import Android.widget.textview;public class MainActivity    Extends Appcompatactivity {public static final int updata_view = 1;    Private TextView TextView;    Private Button changecontent;    Private EditText inputcontent;    Private Thread Mthread; Private Handler Mhandler = new Handler () {@Override public void Handlemessage (Message msg) {SWI TCH (msg.what) {case updata_view:string minputcontent = Inputcontent.gettext (). Tostrin                    g ();                    Textview.settext (minputcontent);                Break            Default:break;    }        }    }; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate(savedinstancestate);        Setcontentview (R.layout.activity_main);        TextView = (TextView) Findviewbyid (R.id.testhandler);        Inputcontent = (EditText) Findviewbyid (r.id.inputcontent);        Changecontent = (Button) Findviewbyid (r.id.changeviewcontent);    Changecontent.setonclicklistener (New Myonclicklistener ()); } Private class Myonclicklistener implements View.onclicklistener {@Override public void OnClick (View VI EW) {switch (View.getid ()) {Case r.id.changeviewcontent:mthread = new thre                    AD (runnable);                    Mthread.start ();                Break            Default:break; }}} Runnable Runnable = new Runnable () {@Override public void run () {Message mes            Sage = new Message ();            Message.what = Updata_view;        Mhandler.sendmessage (message); }    };}

first, a new Handler,handlemessage method is used to process the sent message. Thread inside sends a message, and then updates the contents of the TextView, performing such as the following:

Watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqv/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70/gravity /center "width=" "height=" >

The main handler has been completed, the following further study under the Asynctask.

Asynctask is an auxiliary class that facilitates writing background threads and UI threads.

Its internal implementation is a thread pool. Each background is committed to the thread pool to run. Asynctask has three template functions:

1. Params: The type of the parameters passed to the background task.

2, Progress: Background calculation in the process of operation, the progressive unit type.

3. Result: The type of the result returned by the background run.

When marking a type that is not required, only void is required.

Asynctask needs to rewrite 5 methods. Each is:

1, OnPreExecute method: Ready to execute. The callback function is called by the UI thread immediately after the task is executed. It is generally possible to display a running progress bar.

2. Doinbackground (Params ...) Method: Executing in the background. This is usually done in a time-consuming background calculation where the results are returned to the function, assuming that the third parameter of the asynctask is void and does not need to be returned, where the UI cannot be updated. But can call Publishprogress (Progress ...) Method is complete.

3, Onprogressupdate (Progress ...) Method: Progress update, UI thread in Publishprogress (Progress ...) Called when the method call is complete. General dynamic display of a progress.

4, OnPostExecute (Result) method: Finished background task, will return, here can do some UI operation, such as reminding the task to run the results. and close the Progress Bar dialog box, and so on.

5. Oncancelled method: Cancels the task, called when the Cancel () method of Asynctask is called.

The above example is done by Asynctask. The code for handler is not removed, such as the following code:

Package Com.example.jared.handlertest;import Android.os.asynctask;import Android.os.handler;import Android.os.message;import Android.support.v7.app.appcompatactivity;import Android.os.bundle;import Android.view.view;import Android.widget.button;import Android.widget.edittext;import Android.widget.TextView;    public class Mainactivity extends appcompatactivity {public static final int updata_view = 1;    Private TextView TextView;    Private Button changecontent;    Private EditText inputcontent;    Private Thread Mthread; Private Handler Mhandler = new Handler () {@Override public void Handlemessage (Message msg) {SWI TCH (msg.what) {case updata_view:string minputcontent = Inputcontent.gettext (). Tostrin                    g ();                    Textview.settext (minputcontent);                Break            Default:break;    }        }    }; @Override protected void OnCreate (Bundle savedinstancestATE) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        TextView = (TextView) Findviewbyid (R.id.testhandler);        Inputcontent = (EditText) Findviewbyid (r.id.inputcontent);        Changecontent = (Button) Findviewbyid (r.id.changeviewcontent);    Changecontent.setonclicklistener (New Myonclicklistener ()); } Private class Myonclicklistener implements View.onclicklistener {@Override public void OnClick (View VI EW) {switch (View.getid ()) {case r.id.changeviewcontent://mthread = new Th                   Read (runnable);                    Mthread.start ();                    Changeviewcontenttask task = new Changeviewcontenttask ();                    Task.execute ();                Break            Default:break; }}} class Changeviewcontenttask extends Asynctask<void, Integer, boolean> {@Override p rotected Boolean DoINbackground (Void ... voids) {return null; } @Override protected void Onprogressupdate (Integer ... values) {} @Override protected            void OnPostExecute (Boolean b) {String minputcontent = Inputcontent.gettext (). toString ();        Textview.settext (minputcontent);        } @Override protected void OnPreExecute () {} @Override protected void oncancelled () { }} Runnable Runnable = new Runnable () {@Override public void run () {Message Messa            GE = new Message ();            Message.what = Updata_view;        Mhandler.sendmessage (message); }    };}
This instantiates a task. Then Task.execute (), can be run, the effect as above will not add a map.

The learning Path of Android development--the first experience of asynchronous message Handler,message,looper and Asynctask

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.