Android Asynchronous Task Asynctask

Source: Internet
Author: User

 Packagecom.example.ansyctest;ImportJava.io.ByteArrayOutputStream;ImportJava.io.InputStream;ImportOrg.apache.http.HttpResponse;Importorg.apache.http.client.HttpClient;ImportOrg.apache.http.client.methods.HttpGet;Importorg.apache.http.impl.client.DefaultHttpClient;Importandroid.app.Activity;ImportAndroid.app.Dialog;ImportAndroid.app.ProgressDialog;ImportAndroid.graphics.Bitmap;Importandroid.graphics.BitmapFactory;ImportAndroid.os.AsyncTask;ImportAndroid.os.Bundle;ImportAndroid.util.Log;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.ImageView;/*** * Asynctask * Asynchronous task * A simple thread that is simpler for the UI thread, can be executed in the background, and publishes the data in the UI thread * is an auxiliary class around threads and handler, no need to build a wireframe * is a short time Tasks, * * Async tasks are defined as threads running in the background, publish results to UI interface * There are three generic parameters * asynctask ' s generic types the three types us Ed by an asynchronous task is the Following:params, the type of the parameters sent to the task upon Executio            N. Progress, the type of the Progress units published during the background computation.        result, the type of the result of the background computation. Not all types is always used by an asynchronous task.         To mark a type as U * Params: Parameter type sent when performing a task * Progress: progress unit type performed by background operation * Result: type of background calculation result * * Four steps         * (1) OnPreExecute () Call UI thread before task execution, create task * (2) Doinbackgroud (Params ...)                 * After OnPreExecute execution, Li immediately executes this method, the execution of the background operation will take a long time * The parameters of the asynchronous task is passed to this method, and then the result of the operation is passed to (4), * You can also use Publishprogress (Progress...) Passes the progress of one or more units, shown in (3) in the UI thread * (3) onprogressupdate (Params ...) * In the execution of Publishprogress (P Rogress ...)  After calling the UI thread * (4) OnPostExecute (Result) * When the background operation is finished, the result of the operation is passed to this method as parameter * * * *@authorAdministrator **/ Public classMainactivityextendsActivity {PrivateButton btn; PrivateImageView IV; PrivateString imgpath= "http://www.gwyoo.com/lunwen/jylw/jyyjlw/201603/623467.html"; PrivateProgressDialog Dialog; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); BTN=(Button) Findviewbyid (R.id.button1); IV=(ImageView) Findviewbyid (R.ID.IMAGEVIEW1); Dialog=NewProgressDialog ( This); Dialog.setmax (100); Dialog.settitle (Prompted); Dialog.setmessage ("Download Picture"); Dialog.setcancelable (false);//do not let users cancelDialog.setprogressstyle (progressdialog.style_horizontal); Btn.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {//Performing asynchronous Tasks                Newmytask (). Execute (Imgpath);     }        }); }    /*** *params Pass data type *progress Progress unit type *result background returns the type of result*/    classMyTaskextendsAsynctask<string, Integer,byte[]>{@Overrideprotected voidOnPreExecute () {//The Create key task displays before the task is executed            Super. OnPreExecute ();        Dialog.show (); } @Overrideprotected byte[] doinbackground (String ... params) {byte[] result =NULL; HttpClient HttpClient=Newdefaulthttpclient (); HttpGet HttpGet=NewHttpGet (params[0]); Try{HttpResponse HttpResponse=NULL; Bytearrayoutputstream BAOs=NewBytearrayoutputstream (); if(HttpClient! =NULL&& HttpGet! =NULL) {HttpResponse=Httpclient.execute (HttpGet); }                //total level of access to resources                LongFile_length =httpresponse.getentity (). Getcontentlength (); //the length of the download                LongDownlength = 0; //data for each download                byte[] data =New byte[1024]; //length of each download                intLen = 0; //determine the response code                if(Httpresponse.getstatusline (). Getstatuscode () = = 200) {                    //request succeeded, get data//result= Entityutils.tobytearray (httpresponse.getentity ()); //Get ConnectionsInputStream in =httpresponse.getentity (). getcontent (); //Read Resources                     while((Len=in.read (data))! =-1) {Downlength+=Len; intProgress_value = (int) ((downlength/file_length) *100); //Send Progresspublishprogress (Progress_value); Baos.write (data,0, Len); } result=Baos.tobytearray (); }Else{log.i ("Tag", "Exception"); }            } Catch(Exception e) {e.printstacktrace (); }finally{Httpclient.getconnectionmanager (). Shutdown (); }            returnresult; } @Overrideprotected voidonprogressupdate (Integer ... values) {//Update UISuper. Onprogressupdate (values); Setprogress (values[0]); } @Overrideprotected voidOnPostExecute (byte[] result) {            Super. OnPostExecute (Result); //Bitmap BM = bitmapfactory.decodestream (new Bytearrayinputstream (result));            if(Result = =NULL) {return;} Bitmap BM= Bitmapfactory.decodebytearray (result, 0, result.length);            Iv.setimagebitmap (BM); //            Dialog.dismiss (); }     }}

Android Asynchronous Task 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.