AsyncTask Demo小记

今天搞了一个AsyncTask下载图片的demo,发现下载好的图片失真 都扭曲了,开始还以为是图片大小或是屏幕分辨率的问题,后来检查了一下在用ByteArrayOutputStream写数据的时候犯了错:baos.write(buffer); 后改为:baos.write(buffer, 0, len); 就没有问题了,其实在InputStream is = response.getEntity().getContent();获得输入流以后可以不用把它转换成字节数组就能转换为Bitmap,调用Bitmap bitMap = BitmapFactory.decodeStream(is);这个方法即可,但是直接调用这个方法貌似不能计算出下载进度了?

代码如下:

package com.ylj.asynctask;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends ActionBarActivity implements OnClickListener
{

	private Button btn_download;
	private ImageView iv_picture;
	private ProgressDialog pDialog;
	private String path = "http://img8.zol.com.cn/bbs/upload/20688/20687324_0800.jpg";
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		iv_picture = (ImageView) findViewById(R.id.iv_picture);
		btn_download = (Button) findViewById(R.id.btn_download);
		btn_download.setOnClickListener(this);
	}
	@Override
	public void onClick(View v)
	{
		new DownloadTask().execute(path);
		
	}
	
	private class DownloadTask extends AsyncTask<String, Integer, Bitmap>{

		private Bitmap bitMap;

		@Override
		protected void onPreExecute()
		{
			pDialog = new ProgressDialog(MainActivity.this);
			pDialog.setTitle("下载提示");
			pDialog.setMessage("正在下载中,请稍后...");
			pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			pDialog.setCancelable(false);
			pDialog.show();
			super.onPreExecute();
		}
		
		@Override
		protected Bitmap doInBackground(String... params)
		{
			HttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(params[0]);
			try
			{
				HttpResponse response = client.execute(get);
				if(response.getStatusLine().getStatusCode() == 200){
					long length = response.getEntity().getContentLength();
					InputStream is = response.getEntity().getContent();
					byte[] buffer = new byte[1024];
					int len;
					int count = 0;
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					while((len=is.read(buffer)) != -1){
						count += len;
						baos.write(buffer, 0, len);
						int progress = (int) (((float)count / (float)length) * 100);
						publishProgress(progress);
					}
					byte[] data = baos.toByteArray();
                                // byte[] buffer = EntityUtils.toByteArray(response.getEntity());
					bitMap = BitmapFactory.decodeByteArray(data, 0, data.length);
				//  可以直接用这个方法把InputStream转换为bitmap
				//  bitMap = BitmapFactory.decodeStream(is);
				}
				
			}
			catch (ClientProtocolException e)
			{
				e.printStackTrace();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
			return bitMap;
		}
		
		@Override
		protected void onPostExecute(Bitmap result)
		{
			pDialog.dismiss();
			iv_picture.setImageBitmap(result);
			super.onPostExecute(result);
		}
		
		@Override
		protected void onProgressUpdate(Integer... values)
		{
			pDialog.setProgress(values[0]);
			super.onProgressUpdate(values);
		}
	}
}

布局:

<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"
    tools:context="com.ylj.asynctask.MainActivity" >

    <ImageView  android:id="@+id/iv_picture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"/>
    <Button
        android:id="@+id/btn_download"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="@string/download" />

</RelativeLayout>


你可能感兴趣的:(AsyncTask Demo小记)