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

Android HttpURLConnection 與最簡單的 Handler 通信機制

編輯:關於 Android 程式設計

Handler 機制在 Android 開發中主要用於主線程與子線程的溝通:子線程發起網絡請求並把結果發送給主線程,再由主線程更新 UI。下面是一個使用 HttpURLConnection 訪問網絡並透過 Handler 回傳結果的完整示例:

package com.example.webview;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity implements OnClickListener {
    public static final int SHOW_RESPONSE = 0;
    private TextView reponseText;
    private Button sendButton;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // 接收消息並更新 UI 線程上的控件
            switch (msg.what) {
                case SHOW_RESPONSE:
                    String response = (String) msg.obj;
                    reponseText.setText(response);
                    break;
                default:
                    Toast.makeText(MainActivity.this, "show fail!!", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sendButton = (Button) findViewById(R.id.send_request_id);
        reponseText = (TextView) findViewById(R.id.text_id);
        sendButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        sendRequestWithHttpURLConnection();
    }

    /** 開啟子線程發起網絡請求 */
    private void sendRequestWithHttpURLConnection() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL("https://www.baidu.com");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);  // 連接超時
                    connection.setReadTimeout(8000);     // 讀取超時

                    InputStream inputStream = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(inputStream));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }

                    // 透過 handler 把結果發送給主線程
                    Message message = handler.obtainMessage();
                    message.what = SHOW_RESPONSE;
                    message.obj = response.toString();
                    handler.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }
}

這個示例濃縮了 Handler 通信的經典套路:handler.obtainMessage() 從消息池取一個 Message,設置好 what 與 obj 後透過 sendMessage() 發送;主線程的 handleMessage() 收到後再安全地更新 UI。這樣既遵守了「只有創建 View 的線程才能更新 View」的規則,又實現了子線程網絡請求與主線程界面刷新的解耦。

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