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

Source: Internet
Author: User

In the simple music player, with the handler, and not too much to study, here to learn the next Android under the asynchronous message processing mechanism. The handler used here is mainly that the UI cannot be updated in the thread, and it needs to be handler. 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 containing the update information to the UI thread.

2, MessageQueue: Message queue, used to store all messages published through handler, because it is a queue, so it is first-out.

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

4, Looper: Cycle management MessageQueue, loop out the message in MessageQueue, and give the corresponding handler to deal with.

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 an example. Or, create a new project Handlertest, write a simple layout as follows:

<?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.hand Lertest.        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 and press button to change the contents of the TextView. Write the Mainactivity code as follows:

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); }    };}

here is a new Handler,handlemessage method to process the sent message,thread inside send a message, and then update the contents of TextView, run as follows:

The basic handler has been completed, the following to learn the next asynctask.

Asynctask is an auxiliary class that facilitates writing background threads and UI threads. Its internal implementation is a thread pool, and each backend is committed to the thread pools to execute. Asynctask has three template functions:

1. Params: The parameter type passed to the background task.

2, Progress: Background calculation execution process, progressive unit type.

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

When you mark an unwanted type, just use void.

Asynctask needs to rewrite 5 methods, namely:

1. OnPreExecute method: Ready to run, the callback function is called by the UI thread immediately after the task is executed, and the progress bar can generally be displayed.

2. Doinbackground (Params ...) Method: Running in the background, usually here to perform time-consuming background calculations, the results are returned to the function, if Asynctask's third argument is void, you do not need to return, here can not update the UI, but it is possible to call Publishprogress (Progress ...) Method is complete.

3, Onprogressupdate (Progress ...) Method: Progress update, UI thread in Publishprogress (Progress ...) Called when the method call is complete, and a progress is generally displayed dynamically.

4, OnPostExecute (Result) method: Completes the background task, will return, here can carry on the UI operation, for example reminds the task to execute the result, as well as closes the progress Bar dialog box and so on.

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

The following example is Asynctask, the handler code is not deleted, the code is as follows:

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); }    };}
A task is instantiated here and then Task.execute (); it can be executed, and the effect is not added to the diagram.

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

Related Article

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.