Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android 異步任務AsyncTask

android 異步任務AsyncTask

編輯:關於Android編程

異步任務AsyncTask

AsyncTask主要用來更新UI線程,比較耗時的操作可以在AsyncTask中使用。

AsyncTask是個抽象類,使用時需要繼承這個類,然後調用execute()方法。注意繼承時需要設定三個泛型Params,Progress和Result的類型,如AsyncTask

    Params是指調用execute()方法時傳入的參數類型和doInBackgound()的參數類型一樣Progress是指更新進度時傳遞的參數類型,即於publishProgress()和onProgressUpdate()的參數類型一樣Result是指doInBackground()的返回值類型 上面的說明涉及到幾個方法:
    • doInBackgound() 這個方法是繼承AsyncTask必須要實現的,運行於後台,耗時的操作可以在這裡做
    • publishProgress() 更新進度,給onProgressUpdate()傳遞進度參數(在UI主進程中,執行這個方法)
    • onProgressUpdate() 在publishProgress()調用完被調用,更新進度

      異步任務所使用的三種類型:

      1. Params ,發送到任務的類型參數 執行。
      2. Progress進步的類型單位期間公布 後台計算。
      3. Result,背景的結果的類型 計算。


        \
        \




        使用AsyncTask只要如下三步:

        1、創建AsyncTask的類,並為三個泛型參數指定類型。如果某個泛型參數不需要指定類型,就可將他指定為void

        <喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+PC9wPgo8Y2VudGVyPjxicj4KPC9jZW50ZXI+CjxjZW50ZXI+MqGiuPm+3dDo0qrKtc/WQXN5bmNUYXNrtcTI58/Ct723qKO6PC9jZW50ZXI+CjxjZW50ZXI+PC9jZW50ZXI+CjxjZW50ZXI+PC9jZW50ZXI+CjxwPjwvcD4KPGNlbnRlcj4gICAgICAgKDEpb25QcmVFeGVjdXRlKCk6uMO3vbeovavU2ta00NC688yousTKsbLZ1/dkb0luQmFja2dyb3VuZCgpt723qMewsbu199PDoaPNqLOjuMO3vbeo08PT2s3qs8nSu9Cps/XKvLuvtcTXvLG4uaTX96OsscjI59TavefD5snPz9TKvr34tsjM9bXIo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1tC0tL2oQXN5bmNUYXNrtcRleGV0dWUoKbe9t6iho7HY0OvU2lVJz9+zzNbQtffTw0FzeW5jVGFza7XEyrXA/UFzeW5jVGFza7XEb25QZXJFeGVjdXRlKCmhom9uUG9zdEV4ZWN1dGWjqFJlc3VsdCByZXN1bHSjqaGiZG9JbkJhY2tncm91bmQoUGFyYW1zLi4uLlBhcmFtcyksb25Qcm9ncmVzc1VwZGF0ZaOoUHJvZ3Jlc3MuLi52YWx1ZXOjqbe9t6ijrLK706a4w9PQs8zQ8tSxtPrC67X308OjrLb4ysfT0GFuZHJvaWTPtc2zuLrU8LX308Oho8O/uPZBc3luY1Rhc2vWu8TcsbvWtNDQ0ru0zqOstuC0zrX308O9q7vh0v23otLss6Ohowo8YnI+Cgo8c3Ryb25nPsD919Ojujwvc3Ryb25nPgrPwsPmysdBbmRyb2lkIEFzeW5jVGFza7XEyrnTw8D919OjrLrzzKjWtNDQtcSjrLT4vfi2yMz1oaMKPGltZyBzcmM9"" alt="\">

        package com.example.asynctestdemo;
        
        import java.io.ByteArrayOutputStream;
        import java.io.IOException;
        import java.io.InputStream;
        
        import org.apache.http.HttpEntity;
        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.os.AsyncTask;
        import android.os.Bundle;
        import android.view.View;
        import android.view.View.OnClickListener;
        import android.widget.Button;
        import android.widget.ProgressBar;
        import android.widget.TextView;
        
        public class MainActivity extends Activity {
        	private Button bt_execute;
        	private Button bt_cancel;
        	private ProgressBar progressBar;
        	private TextView textView;
        	MyTask myTask;
        
        	protected void onCreate(Bundle savedInstanceState) {
        		super.onCreate(savedInstanceState);
        		setContentView(R.layout.activity_main);
        		bt_execute = (Button) findViewById(R.id.bt_execute);
        		bt_cancel = (Button) findViewById(R.id.bt_cancel);
        		progressBar = (ProgressBar) findViewById(R.id.progressBar);
        		textView = (TextView) findViewById(R.id.text_view);
        
        		bt_execute.setOnClickListener(new OnClickListener() {
        
        			public void onClick(View v) {
        				// 實例化異步任務MyTask類
        				myTask = new MyTask();
        				myTask.execute("http://www.baidu.com");
        			}
        		});
        
        		bt_cancel.setOnClickListener(new OnClickListener() {
        
        			public void onClick(View v) {
        				myTask.cancel(true);
        			}
        		});
        
        	}
        
        	class MyTask extends AsyncTask {
        
        		// onpreExecute()方法用於,在執行後台任務前,做一些UI操作
        		protected void onPreExecute() {
        			textView.setText("Loading......");
        		}
        
        		// doInBackground()方法,內部執行後台耗時任務操作,但不是不能在此方法內修改UI
        		protected String doInBackground(String... params) {
        			try {
        				HttpClient client = new DefaultHttpClient();
        				HttpGet get = new HttpGet(params[0]);
        				HttpResponse response = client.execute(get);
        				if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        					HttpEntity entity = response.getEntity();
        					InputStream is = entity.getContent();
        					long total = entity.getContentLength();
        					System.out.println(total);
        					ByteArrayOutputStream baos = new ByteArrayOutputStream();
        					byte[] buf = new byte[1024];
        					int count = 0;
        					int length = -1;
        					while ((length = is.read(buf)) != -1) {
        						baos.write(buf, 0, length);
        						count+=length;
        						// 調用publishProgress()方法公布進度,最後onProgressUpdata方法將被執行
        						publishProgress((int) (count/length));
        						//為了更明顯的展現效果,每次暫停0.5s
        						Thread.sleep(500);
        					}
        					return new String(baos.toByteArray(), "utf-8");
        				}
        			} catch (ClientProtocolException e) {
        				e.printStackTrace();
        			} catch (IOException e) {
        				e.printStackTrace();
        			} catch (InterruptedException e) {
        				e.printStackTrace();
        			}
        			return null;
        		}
        
        		// onProgressUpdata方法,用於更新進度信息,例如執行進度條程序
        		protected void onProgressUpdate(Integer... values) {
        			progressBar.setProgress(values[0]);
        			textView.setText("Loading......" + values[0]);
        		}
        
        		// onPostExecute方法,用於在執行完後台任務後,更新UI,顯示結果
        		protected void onPostExecute(String result) {
        			textView.setText(result);
        		}
        
        		// onCacelled方法,用於在取消執行中的任務時,更改UI
        		protected void onCancelled() {
        			textView.setText("cancelled");
        			progressBar.setProgress(0);
        		}
        
        	}
        }




  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved