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

所属分类: 软件编程 / Android 阅读数: 1362
收藏 0 赞 0 分享

本文实例讲述了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 = "https://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程序设计有所帮助。

更多精彩内容其他人还在看

Android控件系列之CheckBox使用介绍

CheckBox和Button一样,也是一种古老的控件,它的优点在于,不用用户去填写具体的信息,只需轻轻点击,缺点在于只有“是”和“否”两种情况,但我们往往利用它的这个特性,来获取用户的一些信息
收藏 0 赞 0 分享

Android控件系列之EditText使用方法

EditText是接受用户输入信息的最重要控件。通过前面课程的学习,您可能会猜到可以利用EditText.getText()获取它的文本,但真正的项目中,可能没那么简单,需要更多的限制,如文本长度限制,是否数字限制等等
收藏 0 赞 0 分享

Android控件系列之TextView使用介绍

TextView类似一般UI中的Label,TextBlock等控件,只是为了单纯的显示一行或多行文本,本文介绍了Android中文本控件TextView的用法和常用属性的用法
收藏 0 赞 0 分享

asynctask的用法详解

Android UI操作并不是线程安全的并且这些操作必须在UI线程中执行,本文将为您介绍asynctask的用法
收藏 0 赞 0 分享

Android开发 旋转屏幕导致Activity重建解决方法

Android开发文档上专门有一小节解释这个问题。简单来说,Activity是负责与用户交互的最主要机制,接下来为您详细介绍
收藏 0 赞 0 分享

Notification与NotificationManager详细介绍

在Android系统中,发一个状态栏通知还是很方便的。下面我们就来看一下,怎么发送状态栏通知,状态栏通知又有哪些参数可以设置
收藏 0 赞 0 分享

android LinearLayout和RelativeLayout组合实现精确布局方法介绍

用android LinearLayout和RelativeLayout实现精确布局此方法适合很适合新人看
收藏 0 赞 0 分享

android listview优化几种写法详细介绍

这篇文章只是总结下getView里面优化视图的几种写法,需要的朋友可以参考下
收藏 0 赞 0 分享

Android应用开发SharedPreferences存储数据的使用方法

SharedPreferences是Android中最容易理解的数据存储技术,实际上SharedPreferences处理的就是一个key-value(键值对)SharedPreferences常用来存储一些轻量级的数据
收藏 0 赞 0 分享

Android之PreferenceActivity应用详解

为了引入这个概率 首先从需求说起 即:现有某Activity专门用于手机属性设置 那么应该如何做呢
收藏 0 赞 0 分享
查看更多