---
title: "android-完整利用AsyncTask实现网络图片下载的实例"
author: "tzq668766"
date: "2011-12-01T17:58:33Z"
tags: []
categories: ["移动开发"]
slug: "android-asynctask"
draft: false
lastmod: "2011-12-01T17:58:33Z"
id: 1288077
url: "https://tangy.iteye.com/blog/1288077"
---

**先看看效果图：**

**![](http://hiphotos.baidu.com/tzq668766/pic/item/5ef96f3cb80e7beccbab1aa82f2eb9389a506b05.jpg)‍**

 

**![](http://hiphotos.baidu.com/tzq668766/pic/item/a405b2009245d6883a72abeda4c27d1ed31b2406.jpg)‍**

**主类：**

 

package com.tangzq;

 

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URL;

 

import com.tangzq.Download\_Progressbar\_AsyncTask.MyAsyncTask;

 

import android.app.Activity;

import android.app.ProgressDialog;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.graphics.Matrix;

import android.os.AsyncTask;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.util.Log;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.ImageView;

import android.widget.ProgressBar;

import android.widget.TextView;

 

public class Download\_ProgressDialog\_AsyncTask extends Activity implements OnClickListener {

 

private static final String LOG\_TAG="Download\_ProgressDialog\_AsyncTask";

    String imgHttp1="http://www.shaswatpatel.com/wp-content/uploads/2011/01/android-software.jpg";

    private TextView txt;

    private Button downImg;

    private ImageView imgView;

    private ProgressDialog progressDialog;

    private Bitmap bitmap;

 

    private static final String SDCARD="/sdcard/";

    private String fileName="networkimg1.png";

    @Override

    protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.download\_progressbar);

    txt=(TextView)findViewById(R.id.txt);

    downImg=(Button)findViewById(R.id.downImg);

    downImg.setOnClickListener(this);

    imgView=(ImageView)findViewById(R.id.imgView);

    progressDialog=new ProgressDialog(this);

    progressDialog.setTitle("图片下载");

    progressDialog.setMessage("正在下载图片...");

    progressDialog.setProgressStyle(ProgressDialog.STYLE\_HORIZONTAL);

 

    }

    @Override

public void onClick(View paramView) {

        new MyAsyncTask().execute(imgHttp1);

}

//保存图片方法

public void saveImg(String fullPath,Bitmap bitmap){

File file=new File(fullPath);

if(file.exists()){

file.delete();

}

try {

FileOutputStream fos=new FileOutputStream(file);

boolean isSaved=bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);

if(isSaved){

fos.flush();

fos.close();

}

Log.e(LOG\_TAG, "文件保存成功");

} catch (FileNotFoundException e) {

Log.e(LOG\_TAG, "保存失败");

e.printStackTrace();

} catch (IOException e) {

Log.e(LOG\_TAG, "保存失败");

e.printStackTrace();

}

 

 

}

//缩放图片方法

public Bitmap scaleBitmap(Bitmap oldBitmap,int newWidth,int newHeight){

//获取原始宽和高

int width=oldBitmap.getWidth();

int height=oldBitmap.getHeight();

//计算缩放比例

float scaleWidth=((float)newWidth)/width;

float scaleHeight=((float)newHeight)/height;

//取得要缩放的Maxtri参数

Matrix matrix=new Matrix();

matrix.postScale(scaleWidth, scaleHeight);

//取得新的图片

Bitmap newBitmap=Bitmap.createBitmap(oldBitmap,0,0,width,height,matrix,true);

return newBitmap;

}

 

/\**

\*AsyncTask定义了三种泛型类型 Params，Progress和Result。

    •Params 启动任务执行的输入参数，比如HTTP请求的URL。 

    •Progress 后台任务执行的百分比。 

    •Result 后台执行任务最终返回的结果，比如String

\*如MyAsyncTask类的三个泛型参数：String,Integer,Bitmap

\*/

 

class MyAsyncTask extends AsyncTask&lt;String,Integer,Bitmap&gt;{

 

@Override

protected Bitmap doInBackground(String... paramArrayOfParams) {

 

//super.run();

ByteArrayOutputStream bos=new ByteArrayOutputStream();

try {

URL url=new URL(paramArrayOfParams\[0]);

HttpURLConnection con=(HttpURLConnection)url.openConnection();

con.setDoInput(true);

con.connect();

InputStream is=con.getInputStream();

//获取文件的大小

int maxSize=con.getContentLength();

int nowSize=0;

byte \[]buffer=new byte\[1024];

int len=-1;

while((len=is.read(buffer))!=-1){

bos.write(buffer,0,len);

bos.flush();

nowSize+=len;

// 如果知道响应的长度，调用publishProgress（）更新进度,传递进度给onProgressUpdate（...）方法     

                    publishProgress(maxSize,nowSize);

}

 

//关闭输入流

is.close();

//关闭连接

con.disconnect();

byte \[]imgBytes=bos.toByteArray();

bitmap=BitmapFactory.decodeByteArray(imgBytes, 0, imgBytes.length);

 

} catch (MalformedURLException e) {

Log.e(LOG\_TAG, "MalformedURLException");

e.printStackTrace();

} catch (IOException e) {

Log.e(LOG\_TAG, "IOException");

e.printStackTrace();

} 

return bitmap;

}

 

@Override

protected void onPreExecute() {

//首先清空图片和进度条

if(null!=bitmap){

imgView.setImageBitmap(null);

progressDialog.setProgress(0);

txt.setText("即将下载......");

 

}

    //1、显示进度条

progressDialog.show();

}

 

@Override

protected void onPostExecute(Bitmap result) {

//下载完成后隐藏进度条

progressDialog.dismiss();

//显示图片

imgView.setImageBitmap(bitmap);

//显示缩放图

//imgView.setImageBitmap(scaleBitmap(result,200,200));

//将图片保存到sdcard中

saveImg(SDCARD+fileName,result);

//结束当前线程

}

 

/*

\* 在publishProgress（...）方法被调用后，

\* UI thread将调用这个方法传递的参数来更新界面上展示任务的进展情况

\* 例如:更新进度条进行。

\*/

@Override

protected void onProgressUpdate(Integer... values) {

progressDialog.setMax(values\[0]);

txt.setText("已下载："+(values\[1]\*100)/values\[0]+"%");

Log.e(LOG\_TAG, "正在下载："+values\[1]);

progressDialog.setProgress(values\[1]);

}

 

 

}

 

 

}

 

**download\_progressbar.xml布局文件**：

 

&lt;?xml version="1.0" encoding="utf-8"?&gt;

&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout\_width="fill\_parent"

    android:layout\_height="fill\_parent"

    android:orientation="vertical" &gt;

 

    &lt;TextView

        android:layout\_width="fill\_parent"

        android:layout\_height="wrap\_content"

        android:text="一步下载图片" 

        android:id="@+id/txt"/&gt;

 

    &lt;Button

        android:id="@+id/downImg"

        android:layout\_width="wrap\_content"

        android:layout\_height="wrap\_content"

        android:text="开始下载图片" /&gt;

 

    &lt;FrameLayout

        android:layout\_width="match\_parent"

        android:layout\_height="wrap\_content" &gt;

 

        &lt;ImageView

            android:id="@+id/imgView"

            android:layout\_width="wrap\_content"

            android:layout\_height="wrap\_content" /&gt;

 

        &lt;ProgressBar

            android:id="@+id/progressBar"

            android:layout\_width="fill\_parent"

            style="?android:attr/progressBarStyleHorizontal"

            android:layout\_height="wrap\_content"

            android:layout\_gravity="center"

            android:visibility="invisible"

            /&gt;

    &lt;/FrameLayout&gt;

&lt;/LinearLayout&gt;