Android Asynctask Detailed

Source: Internet
Author: User

(written in the front: the article was read after the course of the tutorial written, thank http://www.imooc.com/learn/377)

I. Introduction to the basic structure of asynctask

First, as the name implies, Asynctask is an asynchronous task.

Why do you want an asynchronous task?

Because only the UI thread, the main thread, can update the control. The advantage is to ensure UI stability and avoid multithreading to the UI at the same time.

At the same time, the time-consuming task should be executed in the non-main thread, otherwise it will cause blocking and throw a non-responding exception.

Asynctask is a good asynchronous mechanism for Android encapsulation. (Of course, you can also write your own new Thread,handler)

Asynctask is an abstract class that is to be inherited and used as a form of asynctask<params,progress,result>.

The params is the type of the input parameter when the task is started, progress is the type of the progress value returned in the background task execution, and result is the type of the result returned after the background task execution completes. This is described in the following code.

Methods of subclasses:

Doinbackgroud, after inheritance, requires a method that must be overridden to execute the task that will be completed asynchronously. Only the method is executed in a child thread and the UI cannot be updated; The following 3 methods are executed in the main thread, and the UI can be updated.

OnPreExecute, called before executing the operation, is used for initialization.

OnPostExecute, the method that is called automatically after the task executes and passes the result value of the Doinbackgroud into the method, that is, you can do some updating of the UI.

Onprogressupdate, which is executed when Publishprogress is called in the Doinbackgroud method, can update the execution progress of the task.

How to use:

Create a custom in the UI thread that inherits from the Asynctask class,

Precautions:

The Asynctask sample must be created in the UI thread to invoke its Execute method.

The 4 overridden methods are automatically called by the system and cannot be called manually.

Second, use Asynctask to load network pictures and use Asynctask simulation progress bar
There are two buttons on the entry page, respectively, corresponding to the two functions described in title.
Activity_main.xml:
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"    android:layout_width= "Fill_ Parent "    android:layout_height=" fill_parent "    android:orientation=" vertical ">    <button        Android:id= "@+id/button1"        android:layout_width= "match_parent"        android:layout_height= "Wrap_content"        android:text= "Load network pictures asynchronously"/>    <button        android:id= "@+id/button2"        android:layout_width= " Match_parent "        android:layout_height=" wrap_content "        android:text=" simulation progress bar "/></linearlayout>


First, the visibility of ImageView and Progressbar,progressbar in the custom XML is gone, which is not initially visible.

Activity_image.xml:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" android:id= "@+id/image" Android: Layout_width= "Fill_parent" android:layout_height= "fill_parent" > <imageview android:id= "@+id/imageView1 "Android:layout_width=" wrap_content "android:layout_height=" Wrap_content "android:layout_alignparent Left= "true" android:layout_alignparenttop= "true" android:layout_marginleft= "24DP" Android:layout_marg        intop= "146DP"/> <progressbar android:id= "@+id/progressbar1" android:visibility= "Gone" Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:layout_below= "@+id/imageV Iew1 "android:layout_centerhorizontal=" true "android:layout_margintop=" 48DP "/> <textview an Droid:id= "@+id/textview1" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" an Droid:layout_alignparentleft= "True "android:layout_alignparenttop=" true "android:layout_margintop=" 43DP "android:text=" Load Picture: " Android:textappearance= "? Android:attr/textappearancelarge"/></relativelayout>


Activity_progressbar.xml:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    android:layout_width= "Fill_ Parent "    android:layout_height=" fill_parent "     android:padding=" 16DP ">    <progressbar        android : id= "@+id/progressbar2"        style= "? android:attr/progressbarstylehorizontal"        android:layout_width= "Match_ Parent "        android:layout_height=" wrap_content "        android:layout_alignparenttop=" true "        android:layout_ Centerhorizontal= "true"        android:layout_margintop= "209DP"/></relativelayout>


Mainactivity class:

Package Com.example.asynctaskdemo;import Android.os.bundle;import Android.app.activity;import Android.content.intent;import Android.view.menu;import Android.view.view;import Android.view.View.OnClickListener Import Android.widget.button;public class Mainactivity extends Activity {@Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Button button1 = (button) Findviewbyid (R.id.button1); Button1.setonclicklistener (new Onclicklistener () {@ overridepublic void OnClick (View arg0) {//TODO auto-generated method stub intent Intent = new Intent (Mainactivity.this, Loadimageactivity.class); MainActivity.this.finish (); startactivity (intent);}); Button button2 = (button) Findviewbyid (R.id.button2); Button2.setonclicklistener (new Onclicklistener () {@ overridepublic void OnClick (View arg0) {//TODO auto-generated method stub intent Intent = new Intent (Mainactivity.this, Progressbaractivity.class); MainActivity.this.finish (); startactivity (intent);}); @OverridepublIC boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is Present.getmenu Inflater (). Inflate (R.menu.main, menu); return true;}}


The interface is over here. Let's talk about the plays.

Loadimageactivity.java:

Package Com.example.asynctaskdemo;import Java.io.bufferedinputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.net.malformedurlexception;import Java.net.urlconnection;import Android.os.asynctask;import Android.os.bundle;import Android.app.activity;import Android.graphics.Bitmap;import Android.graphics.bitmapfactory;import Android.view.menu;import Android.view.view;import Android.widget.ImageView; Import Android.widget.progressbar;public class Loadimageactivity extends Activity {private ProgressBar ProgressBar; Private ImageView imageview;private String URL = "http://avatar.csdn.net/F/1/0/3_u012422829.jpg";//explain the following three parameters for this class: String is input, is address; bitmap is the result; Progress does not need to return information halfway, so it is Voidclass Loadimageasynctask extends Asynctask<string, Void, bitmap> {@Overrideprotected void OnPreExecute () {//TODO auto-generated method stub progressbar.setvisibility (view.visible); Super.onpreexecute ();} Turn on asynchronous thread execution @overrideprotected Bitmap doinbackground (String ... params) {//TODO auto-generated method stub String url = parAms[0]; Bitmap Bitmap = Null;inputstream is = null;try {//sleep 3s first, otherwise the speed is too fast to see the effect Thread.Sleep (3000); URLConnection urlconnection = new Java.net.URL (URL). OpenConnection (); is = Urlconnection.getinputstream (); Bufferedinputstream Bfis = new Bufferedinputstream (is); bitmap = Bitmapfactory.decodestream (Bfis); Is.close (); Bfis.close ();} catch (Malformedurlexception e) {//TODO auto-generated catch block E.printstacktrace ();} catch (IOException e) {//TODO auto-generated catch block E. Printstacktrace ();} catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace ();} return bitmap; Return to OnPostExecute method} @Overrideprotected void OnPostExecute (Bitmap result) {//TODO Auto-generated method stub progressbar.setvisibility (View.gone); Imageview.setimagebitmap (result); Super.onpostexecute (result);}} @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_image);p Rogressbar = (progressBar) Findviewbyid (r.id.progressbar1); ImageView = (ImageView) Findviewbyid (R.ID.IMAGEVIEW1);/In the main thread can not directly invoke the method overridden in that class, only invoke execute, the system will automatically execute the pre, then execute Doinbackground, after execution, then execute Postnew loadimageasynctask (). Execute (  URL); Parameter passed to Doinbackground method} @Overridepublic Boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; this adds items to th E Action Bar If it is present.getmenuinflater (). Inflate (R.menu.main, menu); return true;}}

In this class we define an inner class Loadimageasynctask, which inherits from Asynctask, and its three arguments are explained in the comments. The new object is then invoked at the start of the interface, calling its Execute method. It is important to note here that we cannot invoke the 4 overridden methods, which are automatically called by the system. After calling execute, the system calls OnPreExecute to initialize the operation, then calls Doinbackground, Doinbackground the returned parameters to OnPostExecute after execution, It is generally done in that way to update the UI. Onprogressupdate,ok is not used here, we have the following examples.


The other one, Progressbaractivity.java:

Package Com.example.asynctaskdemo;import Android.app.activity;import Android.os.asynctask;import android.os.Bundle ; Import Android.view.menu;import android.view.view;import android.widget.progressbar;import android.widget.Toast; public class Progressbaractivity extends Activity {private ProgressBar progressbar;private Progressasynctask Progressasynctask;class Progressasynctask extends Asynctask<void, Integer, void> {@Overrideprotected Void Doinbackground (Void ... arg0) {//TODO automatically generated method stub for (int i = 0; i <; i++) {publishprogress (i);//I value passed to ONPROGRESSUPDA tetry {thread.sleep;} catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace ();}} return null;} @Overrideprotected void Onprogressupdate (Integer ... values) {//TODO auto-generated method stub super.onprogressupdate (values);  Progressbar.setprogress (Values[0]); Update progress} @Overrideprotected void OnPostExecute (void result) {//TODO auto-generated method stub progressbar.setvisibility (View.gone); Toast.maketext (Getapplicationcontext (), "Complete task", Toast.lenGth_short). Show (); Super.onpostexecute (result);}} @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_progressbar);p Rogressbar = (ProgressBar) Findviewbyid (r.id.progressbar2);p rogressasynctask = new Progressasynctask ();p rogressasynctask.execute ();} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;}}

Roughly ibid. Look at the note is very good understanding, do not repeat.

Attach source code: http://pan.baidu.com/s/1o6LwZ6y

Reprint please indicate the source, thank you!

Android Asynctask Detailed

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.