AsyncTask异步访问网络数据

AsyncTask异步访问网络数据


AsyncTask<Params,Progress,Result>


Params : 在处理异步任务的时候需要的类型参数


Progress : 完成的进度


Result : 异步任务返回的结果


<div>2、AsyncTask的执行流程</div><div>    class LoadingImageTask
         extends AsyncTask<String, Integer, InputStream>{
        
         /**
         * 在任务执行之前的方法回调
         * 比如:任务执行之前打开进度对话框
         */
         @Override
         protected void onPreExecute() {
             
         }

         /**
         * 处理异步任务
         */
          @Override
          protected InputStream doInBackground(String... params) {
              
               while(true){
                    //更新进度,publishProgress会自动调用onProgressUpdate方法
                    this.publishProgress(0);
               }
               return null;
          }
        
          /**
          * 任务结束之后的方法回调
          * 比如:任务结束之后关闭进度条对话框
          */
          @Override
          protected void onPostExecute(InputStream result) {
               super.onPostExecute(result);
          }
         
          /**
          * 更新进度
          */
          @Override
          protected void onProgressUpdate(Integer... values) {
              
          }
    }</div>






A、任务执行前,回调onPreExecute()方法
B、任务执行时,调用doInBackground()方法来处理任务,必须调用publishProgress()方法来调用onProgressUpdate()方法更新进度
C、任务结束后,回调onPostExecute()方法





网络上异步下载图片案例


package com.xcl.android;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

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;
import android.widget.TextView;

import com.xcl.asynctask.R;

public class AsyncTask_Acitvity extends Activity {
	private TextView text;
	private ImageView img;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.asynctask);
		ID();

	}

	/**
	 * 找到ID
	 */
	public void ID() {
		text = (TextView) findViewById(R.id.text);
		img = (ImageView) findViewById(R.id.img);
	}

	/**
	 * 
	 * @param 下载网络图片的单击事件
	 */
	public void download(View v) {
		AsyncTask_content asy = new AsyncTask_content();
		asy.execute("http://gson.cn/out/abc.jpg");//启动异步请求

	}

	/**
	 * 
	 * @author 异步类
	 * 
	 */
	class AsyncTask_content extends AsyncTask<String, Integer, byte[]> {
		private ProgressDialog dialog;

		@Override
		protected void onPreExecute() {
			// 在任务执行之前回调
			dialog = new ProgressDialog(AsyncTask_Acitvity.this);
			dialog.setTitle("下载图片");
			dialog.setMessage("正在下载");
			dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			dialog.show();
			super.onPreExecute();
		}

		@Override
		protected byte[] doInBackground(String... arg0) {
			// 处理异步任务
			try {
				URL url = new URL(arg0[0]);
				HttpURLConnection com = (HttpURLConnection) url
						.openConnection();

				int total = com.getContentLength();// 得到总共的字节

				dialog.setMax(total);// 这是进度条最大值

				byte[] bytes = new byte[1024];// 限制一次只能读1024
				byte[] Array = new byte[total];// 存储已经读过的字节

				int indexs = 0;
				InputStream input = com.getInputStream();
				int len = input.read(bytes);

				while (len > 0) {
					for (int i = 0; i < len; i++) {
						Array[i + indexs] = bytes[i];
					}
					indexs += len;
					len = input.read(bytes);
					publishProgress(indexs);
				}

				return Array;
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return null;
		}

		@Override
		protected void onPostExecute(byte[] result) {
			// 任务结束之后回调
			Bitmap bitmap = BitmapFactory.decodeByteArray(result, 0,
					result.length);
			img.setImageBitmap(bitmap);
			dialog.dismiss();

		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// 更新
			int index = values[0];
			dialog.setProgress(index);
		}

	}
}



效果图




  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值