The use of Asynctask tool class-Real download Image instance

Source: Internet
Author: User
Tags set set

Reprint please indicate source: http://blog.csdn.net/blackzhangwei/article/details/51922640 Thank you!
What is Asynctask?
Asynctask, a lightweight asynchronous class provided by Android, can directly inherit Asynctask, implement asynchronous operations in a class, and provide interface feedback about the current level of asynchronous execution (UI progress updates can be implemented through an interface), and finally feedback the results of the execution to the UI main thread.

To implement an asynchronous task that can use the handler+ thread, Android gives us another, more lightweight way to do this, using Asynctask.

Concept:
Asynctask is an abstract class, usually we need to create a class to inherit asynctask to implement an asynchronous task,
Asynctask defines three types of generic parameters: Params,progress,result
Params input parameters for initiating task execution, such as the URL of an HTTP request
Progress represents the type of progress value when performing a task, and the percentage of background task execution
result indicates the results returned after the task is completed, such as String.
This three parameter specifies the type by generics when creating the Asynctask subclass

Asynctask a minimum number of asynchronous loading data to override the following two methods:

Doinbackground (Params ...) is performed in the background, and more time-consuming operations can be placed here. Note that it is not possible to manipulate the UI directly. This method is performed on a background thread, and it usually takes a long time to complete the task's main work. You can call Publicprogress (Progress ...) during execution. To update the progress of the task.
OnPostExecute (Result) is equivalent to the way handler handles the UI, where it is possible to use the resulting processing action UI in Doinbackground. This method is executed on the main thread, and the result of the task execution is returned as a parameter to this method

You also have to rewrite these three methods, if necessary, but not necessarily:

Onprogressupdate (Progress ...) You can use the progress bar to increase user experience. This method executes on the main thread and is used to show the progress of the task execution.
OnPreExecute () Here is the interface when the end user calls Excute, and the progress dialog can be displayed here before the task executes before calling this method.
Oncancelled () The action to be made when the user calls Cancel

Using the Asynctask class, here are a few guidelines to follow:

The instance of the task must be created in the UI thread;
The Execute method must be called in the UI thread;
Do not call OnPreExecute () manually, OnPostExecute (Result)
Doinbackground (Params ...), Onprogressupdate (Progress ...) These several methods;
The task can only be executed once, otherwise the exception will occur when multiple calls are made;

The following starts the example:
Mianfirst.xml manifest file You must remember to add network and SD card write permissions
Add two permissions

    <uses-permission android:name="android.permission.INTERNET"/>    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Main.xml
A text display, a button, and a ProgressBar progress bar

<?xml version= "1.0" encoding= "Utf-8"?><relativelayout  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 " tools:context  =" Com.moliying.black.asynstask_demo. Mainactivity ";     <textview  android:layout _width  = "wrap_content"  android:layout_height  = "wrap_content"  android:text  = "display text"  android:id  = "@+id/ Show_textview " android:layout_alignparenttop  =         "true"  android:layout_centerhorizontal  = "true"  Span class= "Hljs-attribute" >android:layout_margintop  = "45DP" />     <button  android:layout_ Width  = "wrap_content"  android:layout_height< /span>= "wrap_content"  android:text  = "start download picture"  android:id  = @+ Id/download_button " android:onclick  =" Download_click " android:layout_below  =" @+id/ Show_textview " android:layout_centerhorizontal  =" true " android:layout_margintop  =  "49DP" />     <progressbar  style         = "Android:attr/progressbarstylehorizontal"  android:layout_width  = "match_parent"  android:layout_height  = "wrap_content"  android:visibility  =  Android:paddingtop  = "8DP"  android:id  =         "@+id/progressbar"  android:layout_below  = "@+id/show_textview"  Span class= "Hljs-attribute" >android:layout_centerhorizontal  = "true" /> </relativelayout>

Mainactivity:

 PackageCom.moliying.black.asynstask_demo;ImportAndroid.os.AsyncTask;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.widget.ProgressBar;ImportAndroid.widget.TextView;ImportAndroid.widget.Toast;ImportJava.io.BufferedInputStream;ImportJava.io.BufferedOutputStream;ImportJava.io.File;ImportJava.io.FileOutputStream;ImportJava.net.URL;ImportJava.net.URLConnection; Public  class mainactivity extends appcompatactivity {TextView Mshow_textview;//Display barProgressBar Mprogressbar;//progress bar    @Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);        Mshow_textview = (TextView) Findviewbyid (R.id.show_textview);    Mprogressbar = (ProgressBar) Findviewbyid (R.id.progressbar); } Public void Download_click(View v) {//Cannot create an object after executing execute repeatedly, can only be used once        NewMyasycntask (). Execute ("Http://pic.syd.com.cn/0/100/41/13/100411386_000000003ed47604.jpg");//Put the first URL parameter by means of the method}/** * Implement an asynchronous Real download task * /Class Myasycntask extends Asynctask<string, Integer, string> {Private Static Final intFlag_con_len =0x1;//Set ProgressBar Total size tag        Private Static Final intFlag_updata =0x2;//Set markup for growth        /** * This method is called in the UI thread, the instantiation Myasynctask starts the call when the task is executed, and some preparation work is done in the method */        @Override        protected void OnPreExecute() {Super. OnPreExecute (); Mprogressbar.setvisibility (view.invisible);//set to show progress barMprogressbar.setprogress (0);//Initial value progress bar is 0Toast.maketext (mainactivity. This,"Start Download", Toast.length_short). Show (); }/** * Executes in a subsequent thread, OnPreExecute, represents a background task, performs a task that needs to be done in a method * The method does not run in the UI thread, primarily for asynchronous operations, where the space in the UI cannot be set Set and modify * but you can invoke the Publishprogress method to trigger Onprogressupdate to manipulate the UI * @param params * @return          */        @Override        protectedStringDoinbackground(String ... params) {Try{//Establish connectionURL url =NewURL (params[0]);//Set incoming first parameterURLConnection con = url.openconnection ();//Open Read URL                intConlen = Con.getcontentlength ();//Get the size of the resource                //Set the maximum value of the progress bar based on the size of the resource                //This method triggers the Onprogressupdate method to pass in, the first one is the token, the second is the value, which is equivalent to key and value (understandable)Publishprogress (Flag_con_len, Conlen);//Buffered stream read WriteBufferedinputstream in =NewBufferedinputstream (Con.getinputstream ()); Bufferedoutputstream out =NewBufferedoutputstream (NewFileOutputStream (NewFile ("/sdcard/black.jpg")));//Start read Write file Operation                intLen =-1;byte[] bytes =New byte[1024x768]; while(len = in.read (bytes))! =-1) {out.write (bytes,0, Len); Out.flush ();//Publish current progress value, callback Onprogressupdate method, set growth marker and value per incrementPublishprogress (Flag_updata, Len);                } out.close ();            In.close (); }Catch(Exception e) {//error will return failure display                return "Error"; }return "Success"; }/** * is executed after calling the Publishprogress method to update the progress value (executed in the UI thread) * @param values */        @Override        protected void onprogressupdate(Integer ... values) {Super. onprogressupdate (values);Switch(values[0]) {//value[0] Represents a tag                 CaseFLAG_CON_LEN:mProgressBar.setMax (values[1]);//value[1] Indicates the maximum progress value passed in                     Break; CaseFLAG_UPDATA:mProgressBar.incrementProgressBy (values[1]);//Here Value[1] indicates the incoming growth progress value                     Break; }        }/** * Doinbackground The task is returned, executes the method, ends the task (execution in the UI thread, can be set on the UI) * @param s */        @Override        protected void OnPostExecute(String s) {Super. OnPostExecute (s);if(s = ="Success") {Mshow_textview.settext ("Download succeeded"); Toast.maketext (mainactivity. This,"Download succeeded", Toast.length_short). Show (); }Else{Mshow_textview.settext ("Download Failed"); Toast.maketext (mainactivity. This,"Failed", Toast.length_short). Show (); } mprogressbar.setvisibility (View.gone);//Do not show when download is complete}    }}


Download links can put their own links

The use of Asynctask tool class-Real download Image instance

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.