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

利用 Handler 打造簡易網絡請求框架

編輯:關於 Android 程式設計

本文將利用 Handler 機制製作一個簡易的網絡請求框架。

核心思路是:UI 在 request 時傳入 UI 中的 Handler,同時將請求的 Runnable 推入工作線程對應的 Handler;工作線程中的 Handler 調用完畢後,再透過傳入的 UI Handler 把數據送回 UI 更新頁面。說白了,UI 中的 Handler 負責數據傳遞,工作線程中的 Handler 負責請求的隊列與調度。

工作線程

public class SvrBgThread extends Thread {
    private static String TAG = "SvrBgThread";
    private Handler mBgTaskHandler;

    public static final class TaskCmd {
        public static final int ACCEPT_MSG = 1;      // 接收後台消息
        public static final int REFUSE_MSG = ACCEPT_MSG + 1; // 拒絕後台消息
        public static final int EXIT_TASK = REFUSE_MSG + 1;  // 退出後台線程
    }
    private Runnable currentRunnable;

    @Override
    public void run() {
        synchronized (SvrBgThread.this) {
            Looper.prepare();
            mBgTaskHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    int what = msg.what;
                    switch (what) {
                        case TaskCmd.ACCEPT_MSG:
                            break;
                        case TaskCmd.REFUSE_MSG:
                            cancelTask(currentRunnable);
                            break;
                        case TaskCmd.EXIT_TASK:
                            Looper.getMainLooper().quit();
                            break;
                    }
                }
                @Override
                public void dispatchMessage(Message msg) {
                    if (msg.getCallback() != null) {
                        currentRunnable = msg.getCallback();
                    }
                    super.dispatchMessage(msg);
                }
            };
            Looper.loop();
        }
    }

    private void cancelTask(Runnable runnable) {
        if (runnable == null) {
            return;
        }
    }

    public synchronized void cancelCurrentTask() {
        cancelTask(currentRunnable);
    }

    public synchronized void cancelAllTask() {
        if (mBgTaskHandler == null) return;
        mBgTaskHandler.removeCallbacksAndMessages(null);
        cancelCurrentTask();
    }

    public synchronized Handler getBgTaskHandler() {
        return mBgTaskHandler;
    }

    public synchronized void exit() {
        if (mBgTaskHandler == null) return;
        mBgTaskHandler.sendEmptyMessage(TaskCmd.EXIT_TASK);
    }
}

在 Thread 中實例化 Handler 後,消息隊列就準備好了,Looper.loop() 會不斷從隊列中取出 Message 執行。這樣耗時的網絡請求就在工作線程中執行(在主線程會 ANR),同時也具備了請求隊列與調度能力。利用 Android 的 Handler 機制,我們免去了自己控制消息隊列的麻煩。

請求接口

public interface IStudentProvider {
    String URL_STUDENT = "datainfo/getStudentInfo";

    /** 統一的學生信息接口 */
    boolean requestStudentInfo(Handler uiHandler, String url, int msgType);
}

其中 uiHandler 是 UI 中的 Handler,負責數據傳回 UI;msgType 是該請求的標識,用來匹配請求(解決 ListView Item 復用導致的數據變動問題,思路與 setTag 後匹配 Tag 一樣)。

接口實現

public class StudentProvider implements IStudentProvider {
    public static final String TAG = "StudentProvider";
    private SvrBgThread mSvrBgThread;

    private StudentProvider() {
        super();
        mSvrBgThread = new SvrBgThread();
    }

    private static class InstanceHolder {
        static final StudentProvider INSTANCE = new StudentProvider();
    }

    /** 單例模式,延遲加載 */
    public static StudentProvider getInstance() {
        return InstanceHolder.INSTANCE;
    }

    public void init() {
        mSvrBgThread.setName(TAG);
        mSvrBgThread.start();
    }

    @Override
    public boolean requestStudentInfo(Handler uiHandler, String url, int msgType) {
        if (uiHandler == null || url == null) {
            return false;
        }
        HttpGet httpGet = null;
        try {
            httpGet = HttpClientProxy.getJsonHttpGet(requestUrl);
        } catch (UnsupportedEncodingException e) {
            Log.e(TAG, "Exception", e);
            return false;
        } catch (JSONException e) {
            Log.e(TAG, "Exception", e);
            return false;
        }
        Student student = new Student();
        HttpRequestRunnable requestRunnable = new HttpRequestRunnable(uiHandler, student, msgType, httpGet);
        if (mSvrBgThread == null || !mSvrBgThread.isAlive()) {
            Log.e(TAG, "svrBgThread not initialized !");
            return false;
        }
        // 將具體請求推入工作線程的 Handler
        return mSvrBgThread.getBgTaskHandler().post(requestRunnable);
    }
}

注意在 init() 中對工作線程的實例化。在 requestStudentInfo 中透過構造 HttpRequestRunnable 封裝具體請求,再推入工作線程的 Handler。當 Handler 取出該 Runnable 執行後就得到請求結果,其中 HttpClientProxy 提供具體的請求方式(post、get、put 等)。

HttpRequestRunnable

public class HttpRequestRunnable implements Runnable {
    private Handler mMsgHandler;
    private IUserDataBuilder mUserData;
    private int msgType;
    private HttpUriRequest httpUriRequest;

    public HttpRequestRunnable(Handler msgHandler, IUserDataBuilder userData, int msgType, HttpUriRequest httpUriRequest) {
        this.mMsgHandler = msgHandler;
        this.mUserData = userData;
        this.msgType = msgType;
        this.httpUriRequest = httpUriRequest;
    }

    /** 處理服務端響應數據 */
    private void handleResponse(IUserDataBuilder databuilder, HttpResponse response) throws Exception {
        int StatusCode = response.getStatusLine().getStatusCode();
        switch (StatusCode) {
            case HttpStatus.SC_NOT_FOUND:
                databuilder.setServerRet(ServerRet.NOTFOUND);
                throw new Exception();
            case HttpStatus.SC_UNAUTHORIZED:
                databuilder.setServerRet(ServerRet.UNAUTHORIZED);
                throw new Exception();
            case HttpStatus.SC_OK:
                databuilder.setServerRet(ServerRet.OK);
                JSONObject retJsonObject = createJSONFromHttpEntity(response.getEntity());
                if (retJsonObject == null) {
                    retJsonObject = HttpUtil.createHttpJson(ServerRet.ILLEGAL_STATE_EXCEPTION);
                    databuilder.setServerRet(ServerRet.ILLEGAL_STATE_EXCEPTION);
                }
                databuilder.parseJson(retJsonObject);
                break;
            default:
                throw new Exception();
        }
    }

    /** 提取 HTTPEntity 中的 JSON 對象 */
    private JSONObject createJSONFromHttpEntity(HttpEntity httpEntity) {
        JSONObject jsonObj = null;
        String entity = null;
        try {
            entity = EntityUtils.toString(httpEntity, HttpClientProxy.ENCODING);
            jsonObj = new JSONObject(entity);
        } catch (Exception e) {
            Log.e(TAG, "Exception", e);
        }
        return jsonObj;
    }

    @Override
    public void run() {
        if (!isConditionMet()) {
            return;
        }
        try {
            HttpClient client = HttpClientProxy.httpClientBuilder();
            HttpResponse response = client.execute(mHttpUriRequest);
            handleResponse(mUserDatabuilder, response);
            client.getConnectionManager().shutdown();
        } catch (Exception e) {
            if (httpUriRequest.isAborted()) {
                mUserData.setServerRet(ServerRet.CLIENT_ABORT_REQUEST);
            } else {
                mUserData.setServerRet(transformException(e));
            }
        } finally {
            synchronized (mMsgHandler) {
                Message message = Message.obtain(mMsgHandler, msgType, mUserData);
                boolean success = mMsgHandler.sendMessage(message);
                if (!success) {
                    Log.e(TAG, "send message back to user fail");
                }
            }
        }
    }

    private boolean isConditionMet() {
        if (mUserData == null || mMsgHandler == null || httpUriRequest == null) {
            return false;
        }
        return true;
    }
}

HttpRequestRunnable 的構造參數分別是 UI 中的 Handler、請求結果對象、請求標志與請求方式。它負責請求執行,結束後把數據設置到 UI 的 Handler(Message.obtain(mMsgHandler, msgType, mUserData))。

數據解析

IUserDataBuilder 是所有實體類需要實現的接口,必須包含解析 JSON 的過程,以及設置與獲取請求結果:

public interface IUserDataBuilder {
    /** 將 JSON 數據解析成用戶期望的數據類型 */
    boolean parseJson(JSONObject jsonObject) throws Exception;
    ServerRet getServerRet();
    void setServerRet();
}

ServerRet 是請求結果的枚舉。以 Student 為例:

public class Student implements IUserDataBuilder {
    private ServerRet mServerRet;
    private String name;
    private int age;
    private String mAddr;

    @Override
    public boolean parseJson(JSONObject jsonObject) throws Exception {
        if (jsonObject == null) {
            return false;
        }
        Student temp = HttpUtils.fromJson(jsonObject.toString(), Student.class);
        name = temp.getName();
        age = temp.getAge();
        mAddr = temp.getAddr();
        return true;
    }
    public String getName() { return name; }
    public int getAge() { return age; }
    public String getAddr() { return mAddr; }
    @Override
    public ServerRet getServerRet() { return null; }
    @Override
    public void setServerRet() { }
}

parseJson 中使用 Gson 解析 JSON:

public static <T> T fromJson(String jsonStr, Class<T> mClass) {
    Gson mGson = new Gson();
    return mGson.fromJson(jsonStr, mClass);
}

使用方式

public class StudentInfoActivity extends Activity {
    public static final String TAG = "StudentInfoActivity";
    public static final String URL = "https://10.10.12.158:8080";
    public static final int MSGTYPE = 1;

    private static Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MSGTYPE) {
                Student student = (Student) msg.obj;
                if (student.getServerRet() == ServerRet.OK) {
                    Log.i(TAG, student.toString());
                } else {
                    Log.i(TAG, "student parse failed");
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        IStudentProvider studentProvider = StudentProvider.getInstance();
        studentProvider.requestStudentInfo(handler, URL, MSGTYPE);
    }
}

最後記得把 StudentProvider.getInstance().init() 放在 Application 的 onCreate 中,在程序啟動時初始化,退出時 cancel。

總結

在 UI 發送請求時,把 UI 中的 Handler 傳入具體請求方法,在其中實現 HttpRequestRunnable,再推入工作線程 Handler 的 MessageQueue。當 Handler 輪詢執行到 HttpRequestRunnable 時,執行具體請求並把 JSON 解析為實體類,然後傳回 UI 的 Handler 更新界面。

弊端:相比 Volley、OkHttp、xUtils 等開源庫,使用 Handler 實現請求較為麻煩、不易擴展,且連續執行多個請求時是串行執行,並發性不好。本文旨在體會 Handler 另一種不常見的用法,深入理解 Handler 機制的原理。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved