Android入門筆記之AsyncTask

Android入門筆記之AsyncTask

<1>簡介

多線程是android重要的機制之一。

<2>關鍵步驟

       Android中通過AsyncTask和標準的Thread類來提供線程服務,將某些操作從主UI現呈上分離開來。

 

       AsyncTask是抽象類,子類必須實現抽象方法doInBackground(Params... p) ,在此方法中實現任務的執行工作,比如連接網絡獲取數據等。通常還應該實現onPostExecute(Result r)方法,因爲應用程序關心的結果在此方法中返回。需要注意的是AsyncTask一定要在主線程中創建實例。AsyncTask定義了三種泛型類型 Params,Progress和Result。

    * Params 啓動任務執行的輸入參數,比如HTTP請求的URL。
    * Progress 後臺任務執行的百分比。
    * Result 後臺執行任務最終返回的結果,比如String。

      AsyncTask 的執行分爲四個步驟。每一步都對應一個回調方法,需要注意的是這些方法不應該由應用程序調用,開發者需要做的就是實現這些方法。在任務的執行過程中,這些方法被自動調用。

    * onPreExecute() 當任務執行之前開始調用此方法,可以在這裏顯示進度對話框。
    * doInBackground(Params...) 此方法在後臺線程執行,完成任務的主要工作,通常需要較長的時間。在執行過程中可以調用publicProgress(Progress...)來更新任務的進度。
    * onProgressUpdate(Progress...) 此方法在主線程執行,用於顯示任務執行的進度。
    * onPostExecute(Result) 此方法在主線程執行,任務執行的結果作爲此方法的參數返回。

<3>出現的問題

       無

<4>代碼及解釋

       AsyncActivity:

package com.activity;

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.test.R;

public class AsyncActivity extends Activity{
	/**   
	 * @ProjectName:  [androidtest] 
	 * @Package:      [com.activity.AsyncActivity.java]  
	 * @ClassName:    [AsyncActivity]   
	 * @Description:    
	 * @Author:       [gmj]   
	 * @CreateDate:   [2013-9-6 下午7:33:52]   
	 * @Version:      [v1.0] 
	 */
	private TextView message;
    private Button open;
    private EditText url;

    @Override
    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_async);
       message= (TextView) findViewById(R.id.async_view);
       url= (EditText) findViewById(R.id.async_text);
       open= (Button) findViewById(R.id.async_but);
       open.setOnClickListener(new View.OnClickListener() {
           public void onClick(View arg0) {
              connect();
           }
       });

    }
    
    private void connect() {
        PageTask task = new PageTask(this);
        task.execute(url.getText().toString());
    }
    
    class PageTask extends AsyncTask<String, Integer, String> {
        // 可變長的輸入參數,與AsyncTask.exucute()對應
        ProgressDialog pdialog;
        public PageTask(Context context){
            pdialog = new ProgressDialog(context, 0);   
            pdialog.setButton("cancel", new DialogInterface.OnClickListener() {
            		public void onClick(DialogInterface dialog, int i) {
            		dialog.cancel();
            		}
            });
            pdialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
	             public void onCancel(DialogInterface dialog) {
	              finish();
	             }
            });
            pdialog.setCancelable(true);
            pdialog.setMax(100);
            pdialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pdialog.show();
        }
        @Override
        protected String doInBackground(String... params) {

            try{

               HttpClient client = new DefaultHttpClient();
               // params[0]代表連接的url
               HttpGet get = new HttpGet(params[0]);
               HttpResponse response = client.execute(get);
               HttpEntity entity = response.getEntity();
               long length = entity.getContentLength();
               InputStream is = entity.getContent();
               String s = null;
               if(is != null) {
                   ByteArrayOutputStream baos = new ByteArrayOutputStream();

                   byte[] buf = new byte[128];

                   int ch = -1;

                   int count = 0;

                   while((ch = is.read(buf)) != -1) {

                      baos.write(buf, 0, ch);

                      count += ch;

                      if(length > 0) {
                          // 如果知道響應的長度,調用publishProgress()更新進度
                          publishProgress((int) ((count / (float) length) * 100));
                      }

                      // 讓線程休眠100ms
                      Thread.sleep(100000);
                   }
                   s = new String(baos.toByteArray());              }
               // 返回結果
               return s;
            } catch(Exception e) {
               e.printStackTrace();

            }

            return null;

        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        @Override
        protected void onPostExecute(String result) {
            // 返回HTML頁面的內容
            message.setText(result);
            pdialog.dismiss(); 
        }

        @Override
        protected void onPreExecute() {
            // 任務啓動,可以在這裏顯示一個對話框,這裏簡單處理
            message.setText("線程啓動");
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            // 更新進度
              System.out.println(""+values[0]);
              message.setText(""+values[0]);
              pdialog.setProgress(values[0]);
        }

     }

}


發佈了29 篇原創文章 · 獲贊 4 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章