Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

AsyncTask 完全指南:回傳資料處理與 GET、POST 請求實作

編輯:關於 Android 開發

Android 採用單執行緒模型,介面(UI)的繪製只能發生在主執行緒中。如果在主執行緒裡執行耗時操作,就會拖慢 UI 繪製與事件響應,甚至觸發「應用無回應」(ANR)問題。因此 Android 明確規定不可在主執行緒進行耗時任務,正解是另開新執行緒來處理。

開啟新執行緒可以透過 new Thread(),或實作 Runnable 介面。那麼,為什麼要特別使用 AsyncTask 呢?

如果直接用 Thread 的 run() 方法,run() 結束後並沒有回傳值,你必須自己建立一套執行緒間的通訊機制。而 AsyncTask 把所有執行緒通訊都封裝成了回呼函式,讓呼叫邏輯更好寫,尤其在異步處理結束後,能透過回呼函式優雅地收尾——畢竟程式設計師都喜歡省事。

除此之外還有一個關鍵原因:Android 4.0 之後禁止在 UI 執行緒中執行網路操作,否則會拋出 android.os.NetworkOnMainThreadException。

AsyncTask 正是 Android 提供的一個輕量級異步任務類,簡單好用,自然是不二之選。

什麼是 AsyncTask

使用時需特別注意:

Task 的實例必須在 UI Thread 中建立;execute 方法也必須在 UI Thread 中呼叫;同一個 Task 只能執行一次,重複呼叫會拋出異常。

泛型化 AsyncTask 與主執行緒資料回傳

所謂「通用 AsyncTask」,指的是要能處理不同型別的請求並回傳不同型別的資料。難不成每種型別都要寫一個 AsyncTask?那也未免太麻煩了。

還有一種常見困惑:我們透過異步任務取得一個物件,然後在下一行立刻使用它,邏輯看似沒問題,運行後卻拋出空指標異常。原因在於 AsyncTask 開啟了新執行緒,但主執行緒並未停下,它會繼續往下跑,而新執行緒此刻可能還在訪問網路、物件尚未就緒。由於網路速度不定,你根本無法確定資料何時到來,網快時一瞬就好,網慢時則要等上一會兒。

下面是一個簡潔的範例。首先,把 Http 類的型別參數(第三個參數即回傳值型別)設為泛型,這樣無論什麼型別的資料都能通用。接著定義一個作為屬性的介面,在 onPostExecute 方法中呼叫其中的 onResponse 方法,再由使用方實作該介面。

這個介面的作用,完全可以理解為一個監聽事件:好比 checkbox 的變更監聽以「是否選中」為觸發條件,這裡則以「是否有資料」為觸發條件,當網路訪問完成並取得資料時便呼叫。由於我們在主執行緒中完成了介面實作,回傳的資料自然任你取用。

public class Http<T> extends AsyncTask<String,Void,T> {
    private OnResponseListener<T> listener;
    public void setListener(OnResponseListener<T> listener) { this.listener = listener; }
    @Override protected T doInBackground(String... params) { return null; }
    @Override protected void onPostExecute(T t) {
        super.onPostExecute(t);
        if (listener!=null){ listener.onResponse(t); }
    }
    // 介面,類似一個監聽事件
    public interface OnResponseListener<T>{ void onResponse(T t); }
}

// 取得資料的測試類
public class Test {
    private User user1=null;
    public void get(){
        Http<User> http=new Http<User>();
        http.setListener(new Http.OnResponseListener<User>() {
            @Override public void onResponse(User user) { user1=user; }
        });
        http.execute("xxx.balabala.com");
    }
}

GET 與 POST 請求的核心實作

發送請求時,參數很容易帶上,請求方式無非 GET 與 POST 兩種。用白話說:GET 相對不安全,參數直接暴露在 URL 上;POST 則相對安全,參數會做編碼處理。下面分別貼出 AsyncTask 在兩種請求下的核心程式碼——doInBackground 方法。

GET

protected T doInBackground(String... params) {
    HttpURLConnection connection=null;
    InputStream is=null;
    ByteArrayOutputStream bos=null;
    try {
        connection=(HttpURLConnection) new URL(params[0]).openConnection();
        connection.setRequestMethod("GET");
        int code=connection.getResponseCode();
        if(code==200){
            is=connection.getInputStream();
            byte [] b=new byte[1024];
            int len=-1;
            bos=new ByteArrayOutputStream();
            while ((len=is.read(b))!=-1){ bos.write(b,0,len); }
            String json=bos.toString("utf-8");
            T t=JSON.parseObject(json,type);
            return t;
        }else{ Log.e("error","網絡訪問失敗==========="+code); }
    } catch (IOException e) { e.printStackTrace(); }
    finally {
        try { if (bos!=null){ bos.close(); } if (is!=null){ is.close(); } }
        catch (IOException e) { e.printStackTrace(); }
        if (connection!=null){ connection.disconnect(); }
    }
    return null;
}

POST — 與 GET 相比,POST 只是多了一段處理參數輸出的程式碼。

protected T doInBackground(String... params) {
    String[] strArr=params[0].split("\\?");
    HttpURLConnection connection=null;
    OutputStream os=null;
    InputStream is=null;
    ByteArrayOutputStream bos=null;
    try {
        connection=(HttpURLConnection) new URL(strArr[0]).openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        os=connection.getOutputStream();
        os.write(strArr[1].getBytes("utf-8"));
        os.close();
        int code=connection.getResponseCode();
        if(code==200){
            is=connection.getInputStream();
            byte [] b=new byte[1024];
            int len=-1;
            bos=new ByteArrayOutputStream();
            while ((len=is.read(b))!=-1){ bos.write(b,0,len); }
            String json=bos.toString("utf-8");
            T t=JSON.parseObject(json,type);
            return t;
        }else{ Log.e("error","網絡訪問失敗==========="+code); }
    } catch (IOException e) { e.printStackTrace(); }
    finally {
        try { if (bos!=null){ bos.close(); } if (is!=null){ is.close(); } }
        catch (IOException e) { e.printStackTrace(); }
        if (connection!=null){ connection.disconnect(); }
    }
    return null;
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved