使用AsyncTask异步任务更新进度

<LinearLayout 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:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="start"
        android:text="开始" />

    <ImageView
        android:id="@+id/iv"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>


本次demo是展示如何使用AsyncTask更新imageView图片,并练习如何自定义dialog控件实现loading,其中(1)、(2)使用系统的自带dialog控件,(3)为自定义控件


demo使用的布局为:



(1)带圈圈的进度条(使用系统自带控件)


package com.example.asyncdemo;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

/**
 * TODO (这里描述这个类的作用 )
 * 
 * @date: 2013-11-30 下午11:52:32
 * @author Hugo
 * @version 1.0.0
 */
public class AsyncTaskDemo extends Activity {

	private ImageView ivImage;
	private static String image_path = "http://ww4.sinaimg.cn/bmiddle/786013a5jw1e7akotp4bcj20c80i3aao.jpg";
	private ProgressDialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		setContentView(R.layout.async_task);

		ivImage = (ImageView) findViewById(R.id.iv);

		dialog = new ProgressDialog(this);
		dialog.setTitle("提示信息");
		dialog.setMessage("正在下载,请稍后...");
		dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);

	}

	public void start(View view) {
		AsyncTask<String, Void, Bitmap> task = new DownloadImgTask();
		task.execute(image_path);
	}

	private class DownloadImgTask extends AsyncTask<String, Void, Bitmap> {
		private Bitmap bitmap;

		@Override
		protected void onPreExecute() {

			super.onPreExecute();

			dialog.show();

		}

		@Override
		protected void onProgressUpdate(Void... values) {

			// TODO Auto-generated method stub
			super.onProgressUpdate(values);

		}

		@Override
		protected void onPostExecute(Bitmap result) {

			super.onPostExecute(result);

			if (null != result) {
				ivImage.setImageBitmap(result);
			}

			dialog.dismiss();
		}

		@Override
		protected Bitmap doInBackground(String... params) {

			HttpClient httpClient = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(params[0]);
			bitmap = null;
			try {
				HttpResponse resp = httpClient.execute(httpGet);

				if (HttpStatus.SC_OK == resp.getStatusLine().getStatusCode()) {
					HttpEntity entity = resp.getEntity();
					Log.i("输入长度", "" + entity.getContentLength());
					
					byte[] bytes = EntityUtils.toByteArray(entity);

					Log.i("输出长度", "" + bytes.length);
					bitmap = BitmapFactory.decodeByteArray(bytes, 0,
							bytes.length);

				}

			} catch (Exception e) {

				e.printStackTrace();

			}
			return bitmap;

		}
	}

}

效果如下:

使用AsyncTask异步任务更新进度_第1张图片


(2)带进度条

package com.example.asyncdemo;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

/**
 * 有进度条的demo
 * 
 * @date: 2013-11-30 下午11:52:32
 * @author Hugo
 * @version 1.0.0
 */
public class AsyncTaskDemo1 extends Activity {

	private ImageView ivImage;
	private static String image_path = "http://ww4.sinaimg.cn/bmiddle/786013a5jw1e7akotp4bcj20c80i3aao.jpg";
	private ProgressDialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		setContentView(R.layout.async_task);

		ivImage = (ImageView) findViewById(R.id.iv);

		dialog = new ProgressDialog(this);
		dialog.setTitle("提示信息");
		dialog.setCancelable(false);
		dialog.setMessage("正在下载,请稍后...");
		dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

	}

	public void start(View view) {
		AsyncTask<String, Integer, Bitmap> task = new DownloadImgTask();
		task.execute(image_path);
	}

	private class DownloadImgTask extends AsyncTask<String, Integer, Bitmap> {

		@Override
		protected void onProgressUpdate(Integer... values) {

			super.onProgressUpdate(values);

			dialog.setProgress(values[0]);

		}

		@Override
		protected void onPreExecute() {

			super.onPreExecute();

			dialog.show();

		}

		@Override
		protected void onPostExecute(Bitmap result) {

			super.onPostExecute(result);

			if (null != result) {
				ivImage.setImageBitmap(result);
			}

			dialog.dismiss();

		}

		@Override
		protected Bitmap doInBackground(String... params) {

			HttpClient httpClient = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(params[0]);
			Bitmap bitmap = null;
			InputStream is = null;
			ByteArrayOutputStream baos = new ByteArrayOutputStream();

			try {
				HttpResponse response = httpClient.execute(httpGet);

				if (HttpStatus.SC_OK == response.getStatusLine()
						.getStatusCode()) {

					// 获取输入流
					is = response.getEntity().getContent();

					// 得到长度
					long length = response.getEntity().getContentLength();
					byte[] buffer = new byte[1024];
					int readLength = 0;
					long total = 0;

					// 读入数据到缓存
					while ((readLength = is.read(buffer)) != -1) {
						total += readLength;

						// 把缓存中的数据写入输出流
						baos.write(buffer, 0, readLength);

						// 更新进度
						publishProgress((int) (total * 100 / length));
					}

					// 解码成bitmap
					byte[] data = baos.toByteArray();
					bitmap = BitmapFactory
							.decodeByteArray(data, 0, data.length);

				}

			} catch (ClientProtocolException e) {

				e.printStackTrace();

			} catch (IOException e) {

				e.printStackTrace();

			} finally {

				try {
					if (null != is) {
						is.close();
						is = null;
					}

					if (null != baos) {
						baos.close();
						baos = null;
					}
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}

			return bitmap;

		}
	}

}

效果图

使用AsyncTask异步任务更新进度_第2张图片










你可能感兴趣的:(使用AsyncTask异步任务更新进度)