android-完整利用AsyncTask实现网络图片下载的实例
先看看效果图: 主类: 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<String,Integer,Bitmap>{ @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布局文件: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="一步下载图片" android:id="@+id/txt"/> <Button android:id="@+id/downImg" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="开始下载图片" /> <FrameLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <ImageView android:id="@+id/imgView" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <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" /> </FrameLayout> </LinearLayout>