天天看點

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);
		}

	}
}
           

效果圖

AsyncTask異步通路網絡資料

繼續閱讀