欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android使用AsyncTask实现多线程下载的方法

程序员文章站 2024-02-27 18:52:15
本文实例讲述了android使用asynctask实现多线程下载的方法。分享给大家供大家参考,具体如下: public class mainactivity ex...

本文实例讲述了android使用asynctask实现多线程下载的方法。分享给大家供大家参考,具体如下:

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 = "//www.jb51.net/images/logo.gif";
  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_main);
    initview();
    initlistener();
  }
  /**
   * 初始化监听器
   */
  private void initlistener() {
    btn1.setonclicklistener(this);
    btn2.setonclicklistener(this);
    btn3.setonclicklistener(this);
  }
  /**
   *
   * 初始化控件
   */
  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) {
    // 点击按钮模拟下载
    mydownloadasy down = new mydownloadasy();
    down.execute(img_uri, arg0.getid() + "");
  }
  /**
   * 1.params,传递给后台任务的参数类型。
   *
   * 2.progress,后台计算执行过程中,进步单位(progress units)的类型。(就是后台程序已经执行了百分之几了。)
   *
   * 3.result, 后台执行返回的结果的类型。
   */
  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("準備運行線程");
      progressbar1.setprogress(0);// 进度条复位
      progressbar2.setprogress(0);// 进度条复位
      progressbar3.setprogress(0);// 进度条复位
    }
    @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("正在后台执行");
      publishprogress(0);
      // 下载图片
      httpclient hc = new defaulthttpclient();
      // 等待2s
      sleepwait();
      publishprogress(50);
      httpget hg = new httpget(arg0[0]);// 获取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); 不能在后台线程操作ui
      return bm;
    }
    /**
     * 等待2s钟
     */
    private void sleepwait() {
      try {
        thread.sleep(2000);
      } catch (interruptedexception e1) {
        // todo auto-generated catch block
        e1.printstacktrace();
      }
    }
    protected void onprogressupdate(integer... values) {
      // 动态更新
      i("進度更新");
      switch (clickbtn) {
      case 1:
        progressbar1.setprogress(values[0]);// 更新进度条的进度
        break;
      case 2:
        progressbar2.setprogress(values[0]);// 更新进度条的进度
        break;
      case 3:
        progressbar3.setprogress(values[0]);// 更新进度条的进度
        break;
      default:
        break;
      }
    }
    protected void onpostexecute(bitmap result) {
      // todo auto-generated method stub
      super.onpostexecute(result);
      i("线程执行完成");
      if (result != null) {
        i("下载图片成功");
        switch (clickbtn) {
        case 1:
          img1.setimagebitmap(result);
          break;
        case 2:
          img2.setimagebitmap(result);
          break;
        case 3:
          img3.setimagebitmap(result);
          break;
        default:
          break;
        }
      } else {
        i("下载图片失败");
      }
    }
    @override
    protected void oncancelled() {
      // todo auto-generated method stub
      super.oncancelled();
      i("取消线程");
      switch (clickbtn) {
      case 1:
        progressbar1.setprogress(0);// 进度条复位
        break;
      case 2:
        progressbar2.setprogress(0);// 进度条复位
        break;
      case 3:
        progressbar3.setprogress(0);// 进度条复位
        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="fill_parent"
    android:layout_centerhorizontal="true" >
    <tablerow>
      <button
        android:id="@+id/btn1"
        android:text="@string/btn1" />
      <progressbar
        android:id="@+id/progressbar1"
        style="?android:attr/progressbarstylehorizontal"
        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/img1"
        android:src="@drawable/ic_launcher" />
    </tablerow>
    <tablerow>
      <button
        android:id="@+id/btn2"
        android:text="@string/btn2" />
      <progressbar
        android:id="@+id/progressbar2"
        style="?android:attr/progressbarstylehorizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
      <imageview
        android:id="@+id/img2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentdescription="@id/img2"
        android:src="@drawable/ic_launcher" />
    </tablerow>
    <tablerow>
      <button
        android:id="@+id/btn3"
        android:text="@string/btn3" />
      <progressbar
        android:id="@+id/progressbar3"
        style="?android:attr/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="10"
    android:targetsdkversion="10" />
  <!-- 访问网络的权限 -->
  <uses-permission android:name="android.permission.internet" >
  </uses-permission>
  <application
    android:allowbackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/apptheme" >
    <activity
      android:name="com.xunfang.asynctackdemo.mainactivity"
      android:label="@string/app_name" >
      <intent-filter>
        <action android:name="android.intent.action.main" />
        <category android:name="android.intent.category.launcher" />
      </intent-filter>
    </activity>
  </application>
</manifest>

更多关于android相关内容感兴趣的读者可查看本站专题:《android调试技巧与常见问题解决方法汇总》、《android开发入门与进阶教程》、《android多媒体操作技巧汇总(音频,视频,录音等)》、《android基本组件用法总结》、《android视图view技巧总结》、《android布局layout技巧总结》及《android控件用法总结

希望本文所述对大家android程序设计有所帮助。