android-first knowledge of Asynctask

Source: Internet
Author: User

Asynctask is a relatively time-consuming task for dealing with some background, which gives the user a good experience. Asynctask extends the thread, enhancing the ability to interact with the main thread.

first introduce the following methods defined in Asynctask:

OnPreExecute (): This method is called by the UI thread before performing a background operation, it can do some preparatory work, display the progress bar before the slice is loaded, etc.

Doinbackground (Params ...) : This method runs in a background thread, and a more time-consuming operation can be written in this method

Onprogressupdate (Progress ...) : This method is only available in Doinbackground (Params ...). method is called when the Publishprogress () method is executed to show the progress of the background task

OnPostExecute (Result): Doinbackground (Params ...) After the method executes, this method is called by the UI thread, which can manipulate the UI in this method, such as displaying the contents of a picture, etc.

Next is the three parameters in the Asynctask :

The Params is the input parameter that initiates the task execution, such as the URL of the HTTP request.

Progress the progress value of the background task execution.

Results that the result background performs the final return of the task.

Finally, an example of the asynchronous loading of a network image would better reflect Asynctask's role:

First access the network remember to join the network access permissions

Place button button in the mainactivity XML file of the 1.Android project

2. Create an activity to display a picture of the network load, create a new inner class inheritance in this activity Asynctask details please refer to the code and comments:

in the XML file:

<Relativelayoutxmlns: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=". Imageactivity " >    <ImageViewAndroid:id= "@+id/imageview"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"/>    <ProgressBarAndroid:id= "@+id/progressbar1"android:visibility= "Gone"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:layout_centerhorizontal= "true"android:layout_centervertical= "true" />   </Relativelayout>

in Activity :

 PackageCom.example.netdemo;ImportJava.io.BufferedInputStream;Importjava.io.IOException;ImportJava.io.InputStream;Importjava.net.MalformedURLException;ImportJava.net.URL;Importjava.net.URLConnection;Importandroid.app.Activity;ImportAndroid.graphics.Bitmap;Importandroid.graphics.BitmapFactory;ImportAndroid.os.AsyncTask;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.view.Window;ImportAndroid.widget.ImageView;ImportAndroid.widget.ProgressBar; Public classImageactivityextendsActivity {PrivateProgressBar ProgressBar; PrivateImageView ImageView; //the address of the picture    Private Static FinalString url= "Http://img3.3lian.com/2013/s1/20/d/57.jpg"; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Requestwindowfeature (Window.feature_no_title);        Setcontentview (R.layout.activity_image);        Findviewbyid (); //Start        Newmyasynctask (). Execute (URL); }    Private voidFindviewbyid () {//TODO auto-generated Method StubProgressBar =(ProgressBar) Findviewbyid (R.ID.PROGRESSBAR1); ImageView=(ImageView) Findviewbyid (R.id.imageview); }    /*** @String The incoming parameter is the URL address of the picture, String type, * @Void progress value is not considered first so return is empty, * @Bitmap background perform task final return result for a picture Bitmap type * @authorCYF **/    classMyasynctaskextendsAsynctask<string, Void, bitmap>{        //The background did not run finished before the preparation work, where we let the original hidden ProgressBar display@Overrideprotected voidOnPreExecute () {//TODO auto-generated Method Stub            Super. OnPreExecute (); //The progress bar shows when running in the backgroundprogressbar.setvisibility (view.visible); }        //network access in the background, get pictures and return@OverrideprotectedBitmap doinbackground (String ... arg0) {//TODO auto-generated Method StubString url=arg0[0]; Bitmap Bitmap=NULL; //Defining network Connection ObjectsURLConnection Connection;            InputStream is; Try{Connection=Newurl (url). OpenConnection (); is=Connection.getinputstream (); Bufferedinputstream bis=NewBufferedinputstream (IS); //parses an input stream into a bipmapbitmap=Bitmapfactory.decodestream (bis);                Is.close ();            Bis.close (); } Catch(malformedurlexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }            returnbitmap; }        //receives the bitmap value returned in the background in the secondary method and sets it to the UI@Overrideprotected voidOnPostExecute (Bitmap result) {//TODO auto-generated Method Stub            Super. OnPostExecute (Result); //the displayed ProgressBar is then set to hiddenprogressbar.setvisibility (View.gone); //set the UI thread to display the picture in this methodImageview.setimagebitmap (Result); }    }}

On the result graph:

Click on the Prepare Interface after button (ProgressBar display indicates loading):

After loading is complete:

Welcome everyone to provide advice, hope to bring you help, thank you.

android-first knowledge of 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.