Android自用—–AsyncTask實現非同步處理任務

來源:互聯網
上載者:User
在開發Android應用時必須遵守單執行緒模式的原則: Android UI操作並不是安全執行緒的並且這些操作必須在UI線程中執行。在單執行緒模式中始終要記住兩條法則:
1. 不要阻塞UI線程
2. 確保只在UI線程中訪問Android UI工具包
    當一個程式第一次啟動時,Android會同時啟動一個對應的主線程(Main Thread),主線程主要負責處理與UI相關的事件,如:使用者的按鍵事件,使用者接觸螢幕的事件以及螢幕繪圖事件,並把相關的事件分發到對應的組件進行處理。所以主線程通常又被叫做UI線程。
   比如說從網上擷取一個網頁,在一個TextView中將其原始碼顯示出來,這種涉及到網路操作的程式一般都是需要開一個線程完成網路訪問,但是在獲得頁面源碼後,是不能直接在網路操作線程中調用TextView.setText()的.因為其他線程中是不能直接存取主UI線程成員

android提供了幾種在其他線程中訪問UI線程的方法。
Activity.runOnUiThread( Runnable )
View.post( Runnable )
View.postDelayed( Runnable, long )
Hanlder
這些類或方法同樣會使你的代碼很複雜很難理解。然而當你需要實現一些很複雜的操作並需要頻繁地更新UI時這會變得更糟糕。

為瞭解決這個問題,Android 1.5提供了一個工具類:AsyncTask,它使建立需要與使用者介面互動的長時間啟動並執行任務變得更簡單。不需要藉助線程和Handler即可實現。
AsyncTask是抽象類別.AsyncTask定義了三種泛型型別 Params,Progress和Result。
  Params 啟動任務執行的輸入參數,比如HTTP請求的URL。
  Progress 背景工作執行的百分比。
  Result 後台執行任務最終返回的結果,比如String。

AsyncTask的執行分為四個步驟,每一步都對應一個回調方法,這些方法不應該由應用程式調用,開發人員需要做的就是實現這些方法。
  1) 子類化AsyncTask
  2) 實現AsyncTask中定義的下面一個或幾個方法
     onPreExecute(), 該方法將在執行實際的後台操作前被UI thread調用。可以在該方法中做一些準備工作,如在介面上顯示一個進度條。
    doInBackground(Params...), 將在onPreExecute 方法執行後馬上執行,該方法運行在後台線程中。這裡將主要負責執行那些很耗時的後台計算工作。可以調用 publishProgress方法來更新即時的任務進度。該方法是抽象方法,子類必須實現。
    onProgressUpdate(Progress...),在publishProgress方法被調用後,UI thread將調用這個方法從而在介面上展示任務的進展情況,例如通過一個進度條進行展示。
    onPostExecute(Result), 在doInBackground 執行完成後,onPostExecute 方法將被UI thread調用,背景計算結果將通過該方法傳遞到UI thread.

為了正確的使用AsyncTask類,以下是幾條必須遵守的準則:
  1) Task的執行個體必須在UI thread中建立
  2) execute方法必須在UI thread中調用
  3) 不要手動的調用onPreExecute(), onPostExecute(Result),doInBackground(Params...), onProgressUpdate(Progress...)這幾個方法
  4) 該task只能被執行一次,否則多次調用時將會出現異常

從網上擷取一個網頁,在一個TextView中將其原始碼顯示出來

Java代碼  
  1. package test.list;   
  2. import java.io.ByteArrayOutputStream;   
  3. import java.io.InputStream;   
  4. import java.util.ArrayList;   
  5.   
  6. import org.apache.http.HttpEntity;   
  7. import org.apache.http.HttpResponse;   
  8. import org.apache.http.client.HttpClient;   
  9. import org.apache.http.client.methods.HttpGet;   
  10. import org.apache.http.impl.client.DefaultHttpClient;   
  11.   
  12. import android.app.Activity;   
  13. import android.app.ProgressDialog;   
  14. import android.content.Context;   
  15. import android.content.DialogInterface;   
  16. import android.os.AsyncTask;   
  17. import android.os.Bundle;   
  18. import android.os.Handler;   
  19. import android.os.Message;   
  20. import android.view.View;   
  21. import android.widget.Button;   
  22. import android.widget.EditText;   
  23. import android.widget.TextView;   
  24.   
  25. public class NetworkActivity extends Activity{   
  26.     private TextView message;   
  27.     private Button open;   
  28.     private EditText url;   
  29.   
  30.     @Override  
  31.     public void onCreate(Bundle savedInstanceState) {   
  32.        super.onCreate(savedInstanceState);   
  33.        setContentView(R.layout.network);   
  34.        message= (TextView) findViewById(R.id.message);   
  35.        url= (EditText) findViewById(R.id.url);   
  36.        open= (Button) findViewById(R.id.open);   
  37.        open.setOnClickListener(new View.OnClickListener() {   
  38.            public void onClick(View arg0) {   
  39.               connect();   
  40.            }   
  41.        });   
  42.   
  43.     }   
  44.   
  45.     private void connect() {   
  46.         PageTask task = new PageTask(this);   
  47.         task.execute(url.getText().toString());   
  48.     }   
  49.   
  50.   
  51.     class PageTask extends AsyncTask<String, Integer, String> {   
  52.         // 可變長的輸入參數,與AsyncTask.exucute()對應   
  53.         ProgressDialog pdialog;   
  54.         public PageTask(Context context){   
  55.             pdialog = new ProgressDialog(context, 0);      
  56.             pdialog.setButton("cancel", new DialogInterface.OnClickListener() {   
  57.              public void onClick(DialogInterface dialog, int i) {   
  58.               dialog.cancel();   
  59.              }   
  60.             });   
  61.             pdialog.setOnCancelListener(new DialogInterface.OnCancelListener() {   
  62.              public void onCancel(DialogInterface dialog) {   
  63.               finish();   
  64.              }   
  65.             });   
  66.             pdialog.setCancelable(true);   
  67.             pdialog.setMax(100);   
  68.             pdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);   
  69.             pdialog.show();   
  70.   
  71.   
  72.         }   
  73.         @Override  
  74.         protected String doInBackground(String... params) {   
  75.   
  76.             try{   
  77.   
  78.                HttpClient client = new DefaultHttpClient();   
  79.                // params[0]代表串連的url   
  80.                HttpGet get = new HttpGet(params[0]);   
  81.                HttpResponse response = client.execute(get);   
  82.                HttpEntity entity = response.getEntity();   
  83.                long length = entity.getContentLength();   
  84.                InputStream is = entity.getContent();   
  85.                String s = null;   
  86.                if(is != null) {   
  87.                    ByteArrayOutputStream baos = new ByteArrayOutputStream();   
  88.   
  89.                    byte[] buf = new byte[128];   
  90.   
  91.                    int ch = -1;   
  92.   
  93.                    int count = 0;   
  94.   
  95.                    while((ch = is.read(buf)) != -1) {   
  96.   
  97.                       baos.write(buf, 0, ch);   
  98.   
  99.                       count += ch;   
  100.   
  101.                       if(length > 0) {   
  102.                           // 如果知道響應的長度,調用publishProgress()更新進度   
  103.                           publishProgress((int) ((count / (float) length) * 100));   
  104.                       }   
  105.   
  106.                       // 讓線程休眠100ms   
  107.                       Thread.sleep(100);   
  108.                    }   
  109.                    s = new String(baos.toByteArray());              }   
  110.                // 返回結果   
  111.                return s;   
  112.             } catch(Exception e) {   
  113.                e.printStackTrace();   
  114.   
  115.             }   
  116.   
  117.             return null;   
  118.   
  119.         }   
  120.   
  121.         @Override  
  122.         protected void onCancelled() {   
  123.             super.onCancelled();   
  124.         }   
  125.   
  126.         @Override  
  127.         protected void onPostExecute(String result) {   
  128.             // 返回HTML頁面的內容   
  129.             message.setText(result);   
  130.             pdialog.dismiss();    
  131.         }   
  132.   
  133.         @Override  
  134.         protected void onPreExecute() {   
  135.             // 任務啟動,可以在這裡顯示一個對話方塊,這裡簡單處理   
  136.             message.setText(R.string.task_started);   
  137.         }   
  138.   
  139.         @Override  
  140.         protected void onProgressUpdate(Integer... values) {   
  141.             // 更新進度   
  142.               System.out.println(""+values[0]);   
  143.               message.setText(""+values[0]);   
  144.               pdialog.setProgress(values[0]);   
  145.         }   
  146.   
  147.      }   
  148.   
  149. }  
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.