Android uses Asynctask to implement multithreaded downloads _android

Source: Internet
Author: User
Tags stub

The example in this article describes how Android uses Asynctask to implement multithreaded downloads. Share to everyone for your reference, specific as follows:

public class Mainactivity extends activity implements Onclicklistener {private Button btn1, btn2, btn3;
  Private ProgressBar progressBar1, ProgressBar2, PROGRESSBAR3;
  Private ImageView Img1, Img2, IMG3;
  private static final String Img_uri = "Yun_qi_img/logo.gif";
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_main);
    Initview ();
  Initlistener ();
    }/** * Initialize listener */private void Initlistener () {Btn1.setonclicklistener (this);
    Btn2.setonclicklistener (this);
  Btn3.setonclicklistener (this);
    /** * * Initialization control/private void Initview () {btn1 = (Button) Findviewbyid (R.ID.BTN1);
    BTN2 = (Button) Findviewbyid (R.ID.BTN2);
    Btn3 = (Button) Findviewbyid (R.ID.BTN3);
    ProgressBar1 = (ProgressBar) Findviewbyid (R.ID.PROGRESSBAR1);
    ProgressBar2 = (ProgressBar) Findviewbyid (R.ID.PROGRESSBAR2); ProgressBar3 = (ProgressBar) Findviewbyid (R.ID.PROGRESSBAR3);
    IMG1 = (ImageView) Findviewbyid (R.ID.IMG1);
    Img2 = (ImageView) Findviewbyid (R.ID.IMG2);
  IMG3 = (ImageView) Findviewbyid (R.ID.IMG3);  @Override public boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action Bar
    If it is present.
    Getmenuinflater (). Inflate (R.menu.main, menu);
  return true;
    @Override public void OnClick (View arg0) {//click button simulate download mydownloadasy down = new Mydownloadasy ();
  Down.execute (Img_uri, Arg0.getid () + "");
   /** * 1.Params, the parameter type passed to the background task. * 2.Progress, background calculates the type of progressive unit (Progress units) during the execution process. (that is, a few percent of the background program has been executed.)
   * * 3.Result, the background to perform the type of returned results.
    * * Class Mydownloadasy extends Asynctask<string, Integer, bitmap> {private static final String TAG = "Asy";
    private int clickbtn = 0;
    private void I (String object) {log.i (TAG, object); @Override protected void OnPreExecute () {//TODO auto-generated method stub supEr.onpreexecute ();
      I ("Ready to run a thread"); 
    Progressbar1.setprogress (0),//progress bar Reset Progressbar2.setprogress (0),//progress bar Reset progressbar3.setprogress (0);//progress bar Reset
      @Override protected Bitmap doinbackground (String ... arg0) {switch (Integer.parseint (arg0[1))) {
        Case R.ID.BTN1:CLICKBTN = 1;
      Break
        Case R.ID.BTN2:CLICKBTN = 2;
      Break
        Case R.ID.BTN3:CLICKBTN = 3;
      Break
      Default:break;
      I ("Performing in the background");
      Publishprogress (0);
      Download Photo HttpClient HC = new Defaulthttpclient ();
      Wait for 2s sleepwait ();
      Publishprogress (50);
      HttpGet hg = new HttpGet (arg0[0]);//Get JB51 logo final Bitmap BM;
        try {HttpResponse hr = Hc.execute (Hg);
      BM = Bitmapfactory.decodestream (Hr.getentity (). getcontent ());
      catch (Exception e) {return null;
      } sleepwait ();
      Publishprogress (100); Mimageview.setimagEbitmap (result);
    Cannot operate UI return bm in background threads;
      /** * wait for 2s clock/private void sleepwait () {try {thread.sleep (2000);
      catch (Interruptedexception E1) {//TODO auto-generated catch block E1.printstacktrace ();
      } protected void Onprogressupdate (Integer ... values) {//Dynamic update I ("Progress Update");
      Switch (CLICKBTN) {case 1:progressbar1.setprogress (values[0]);//Update progress bar progress break;
      Case 2:progressbar2.setprogress (values[0]);//Update progress bar progress break;
      Case 3:progressbar3.setprogress (values[0]);//Update progress bar progress break;
      Default:break; } protected void OnPostExecute (Bitmap result) {//TODO auto-generated method stub Super.onpostexecu
      TE (result);
      I ("Thread execution Complete");
        if (result!= null) {i ("Download picture succeeded");
          Switch (CLICKBTN) {case 1:img1.setimagebitmap (result);
        Break Case 2:img2.setimagebitmap (result);
        Break
          Case 3:img3.setimagebitmap (Result);
        Break
        Default:break;
      } else {i ("Download picture failed"); } @Override protected void oncancelled () {//TODO auto-generated method Stub super.oncancelled (
      );
      I ("Cancel the thread");
      Switch (CLICKBTN) {case 1:progressbar1.setprogress (0);//progress bar reset break;
      Case 2:progressbar2.setprogress (0);//progress bar reset break;
      Case 3:progressbar3.setprogress (0);//progress bar reset break;
      Default:break;

 }
    }
  }
}

XML:

<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 "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= ". Mainactivity "> <tablelayout android:layout_width=" fill_parent "android:layout_height=" an Droid:layout_centerhorizontal= "true" > <TableRow> <button android:id= "@+id/btn1" and roid:text= "@string/btn1" "/> <progressbar android:id=" @+id/progressbar1 "style="? android:attr/p
      Rogressbarstylehorizontal "android:layout_width=" fill_parent "android:layout_height=" Wrap_content "/>" <imageview android:id= "@+id/img1" aNdroid:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:contentdescription= "@id/im
        G1 "android:src=" @drawable/ic_launcher "/> </TableRow> <TableRow> <button Android:id= "@+id/btn2" android:text= "@string/btn2"/> <progressbar android:id= "@+id/progressba R2 "style=" "Android:attr/progressbarstylehorizontal" android:layout_width= "Fill_parent" Android:la yout_height= "Wrap_content"/> <imageview android:id= "@+id/img2" android:layout_width= Tent "android:layout_height=" Wrap_content "android:contentdescription=" @id/img2 "android:src=" @dra
        Wable/ic_launcher "/> </TableRow> <TableRow> <button android:id=" @+id/btn3 " android:text= "@string/btn3" "/> <progressbar android:id=" @+id/progressbar3 "style="? android:a Ttr/progressbarstylehoriZontal "android:layout_width=" fill_parent "android:layout_height=" wrap_content "/> <ImageView
        Android:id= "@+id/img3" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:contentdescription= "@id/img3" android:src= "@drawable/ic_launcher"/> </TableRow> <

 /tablelayout> </RelativeLayout>

Androidmanifast:

<?xml version= "1.0" encoding= "Utf-8"?> <manifest xmlns:android= "http://schemas.android.com/apk/res/"
    Android "package=" Com.xunfang.asynctackdemo "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk android:minsdkversion= "android:targetsdkversion="/> <!--permissions to access the network--> <uses-permission Andro
    Id:name= "Android.permission.INTERNET" > </uses-permission> <application android:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" android:theme= "@style/apptheme" > &L T;activity android:name= "com.xunfang.asynctackdemo.MainActivity" android:label= "@string/app_name" > & lt;intent-filter> <action android:name= "Android.intent.action.MAIN"/> <category "Android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application> </ma

 Nifest>

For more information on Android-related content readers can view the site topics: "Android Debugging techniques and common problems solution summary", "Android Development introduction and Advanced Course", "Android Multimedia operating skills Summary (audio, video, recording, etc.)", " Android Basic Components Usage Summary, Android View tips Summary, Android layout layout tips and Android Control usage summary

I hope this article will help you with the Android program.

Related Article

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.