Android Asynchronous Task Learning notes

Source: Internet
Author: User

Android asynchronous tasks can be very convenient to complete time-consuming operations and update the UI, unlike multithreading also take advantage of Message Queuing, sub-threads send messages to the main thread, the main thread to update the UI. In short, the Android asynchronous task to the multi-threaded interaction for further encapsulation, easy to use.

The following is the asynchronous task demo code:

Completes the asynchronous download picture, updates the interface.

Package Com.example.android_async_task2;import Java.io.bytearrayoutputstream;import Java.io.ioexception;import Java.io.inputstream;import Org.apache.http.httpentity;import Org.apache.http.httpresponse;import Org.apache.http.client.clientprotocolexception;import Org.apache.http.client.httpclient;import Org.apache.http.client.methods.httpget;import Org.apache.http.impl.client.defaulthttpclient;import Org.apache.http.util.entityutils;import Android.app.activity;import Android.app.progressdialog;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.os.asynctask;import Android.os.bundle;import Android.view.menu;import Android.view.view;import Android.view.View.OnClickListener; Import Android.widget.button;import Android.widget.imageview;public class Mainactivity extends Activity {private Button btn=null;private ImageView image=null;private String image_path= "Http://f2.sjbly.cn/m13/0729/1459/6947edn_ 690x459_b.jpg ";p rivate progressdialog Dialog; @Overrideprotectedvoid OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_ Main), btn= (Button) This.findviewbyid (r.id.button1);d ialog=new progressdialog (this);d ialog.settitle ("hint message"); Dialog.setmessage ("Download, please wait ...");//Set the style of the progress bar Dialog.setprogressstyle (progressdialog.style_horizontal);// The screen does not lose focus dialog.setcancelable (false); image= (ImageView) This.findviewbyid (r.id.imageview1); Btn.setonclicklistener ( New Onclicklistener () {@Overridepublic void OnClick (View v) {new MyTask (). Execute (image_path);});} public class MyTask extends asynctask<string,integer,bitmap>{@Overrideprotected void OnPreExecute () { Dialog.show (); Super.onpreexecute ();} @Overrideprotected Bitmap doinbackground (String ... params) {//define a memory stream and do not need to close bytearrayoutputstream out= new Bytearrayoutputstream ();//define an input stream InputStream in=null; Bitmap bitmap=null;//through HttpClient class to obtain network resources HttpClient httpclient=new defaulthttpclient ();//Set Request method (note the request address URL to write!!!) ) HttpGet httpget=new HttpGet (params[0]); try {//Get request status HttpresPonse Httpresponse=httpclient.execute (HttpGet);//Determine request status result code if (Httpresponse.getstatusline (). Getstatuscode () ==200) {/*//entity httpentity httpentity=httpresponse.getentity () that gets a response through an entity class;//Gets the byte array of the entity through an Entity tool class Byte[]data= Entityutils.tobytearray (httpentity);//Create Bitmap object Bitmapfactory.decodebytearray (data, 0, Data.length) through the factory class; */// Gets the input stream in=httpresponse.getentity (). getcontent ();//Gets the total length of the file Long File_length=httpresponse.getentity (). Getcontentlength ();//Calculate total length int total_len=0;int len=0;byte[] buffer=new byte[1024];try{while ((len=in.read (buffer))! = -1) {Total_len+=len;<span style= "color: #ff0000;" >//Scale Calculation formula </span>int value= (int) (total_len/((float) file_length) *100) <span style= "color: #ff6666;" >//the scale of the progress bar is published </span>publishprogress (value);//write output stream out.write (buffer, 0, Len);} The memory output flows into byte array Bitmap=bitmapfactory.decodebytearray (Out.tobytearray (), 0, Out.tobytearray (). length);} catch (Exception e) {}finally{if (in!=null) {in.close ();}}}} catch (Clientprotocolexception e) {//TODO auto-generated catch BLOCKE.PRintstacktrace ();} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} return bitmap;} @Overrideprotected void OnPostExecute (Bitmap result) {Super.onpostexecute (result); Image.setimagebitmap (result); Dialog.dismiss ();} @Overrideprotected void Onprogressupdate (Integer ... values) {super.onprogressupdate (values);d ialog.setprogress ( Values[0]);}} @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;}}
which
Publishprogress (value);
is the ability to send several objects to
The Onprogressupdate () method.

Demo Download: http://download.csdn.net/detail/u014600432/8175337

Android Asynchronous Task Learning notes

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.