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

Android 網路圖片查看器實作:HttpURLConnection 搭配 Handler 異步載入

編輯:關於 Android 開發

Android 網路圖片查看器實作:HttpURLConnection 搭配 Handler 異步載入


這篇記錄如何寫一個簡單的網路圖片查看器:使用者在輸入框貼上圖片網址,按下按鈕後在子執行緒發請求,再把取得的位圖回傳主執行緒顯示。

先來看布局檔:

<?xml version="1.0"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/et_url"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="https://www.baidu.com" />

    <Button
        android:id="@+id/bt_looksource"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="查看圖片" />

    <ScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <ImageView
            android:id="@+id/img_pic"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </ScrollView>
</LinearLayout>

接著是 MainActivity。核心觀念是:網路請求必須放在子執行緒,而更新 UI 只能回到主執行緒,兩者靠 Handler + Message 溝通。

package com.itheima.sourcelook;

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

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
    private EditText et_url;
    private ImageView img_pic;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_url = (EditText) findViewById(R.id.et_url);
        Button bt_looksource = (Button) findViewById(R.id.bt_looksource);
        img_pic = (ImageView) findViewById(R.id.img_pic);
        // 二、設置點擊事件
        bt_looksource.setOnClickListener(this);
    }

    // ☆☆☆1. 在主執行緒建立一個 Handler 物件
    private Handler handler = new Handler() {
        // ☆☆☆2. 重寫 handleMessage,接收子執行緒發來的消息
        public void handleMessage(Message msg) {
            // ☆☆☆5. 接收子執行緒發送的資料
            Bitmap bitmap = (Bitmap) msg.obj;
            // ☆☆☆6. 此處屬於主執行緒,可以更新 UI
            img_pic.setImageBitmap(bitmap);
        };
    };

    @Override
    public void onClick(View v) {
        // 三、取得使用者輸入的 url
        final String url_str = et_url.getText().toString().trim();
        if (TextUtils.isEmpty(url_str)) {
            Toast.makeText(this, "url不能為空", 0).show();
            return;
        }
        // 建立子執行緒做網路請求
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 四、請求 url
                    // 1. 建立 URL 物件
                    URL url = new URL(url_str);
                    // 2. 取得 HttpURLConnection
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    // 3. 設置請求參數與逾時
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(1000 * 10);
                    // 4. 判斷響應碼:200 成功、206 部分成功、300 跳轉、400 錯誤、500 服務器異常
                    int code = connection.getResponseCode();
                    if (code == 200) {
                        // 5. 將讀取流解析成 Bitmap
                        InputStream inputStream = connection.getInputStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        // ☆☆☆3. 子執行緒建立 Message,攜帶資料給主執行緒
                        Message msg = Message.obtain();
                        msg.obj = bitmap;
                        // ☆☆☆4. 用 handler 把 message 發送到主執行緒
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

另外提供一個把輸入流轉字串的通用工具類,之後解析文字資料時很好用:

package com.itheima.sourcelook;

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

public class StreamUtils {
    public static String streamToString(InputStream in) {
        String result = "";
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length = 0;
            while ((length = in.read(buffer)) != -1) {
                out.write(buffer, 0, length);
                out.flush();
            }
            result = out.toString();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

重點整理:

可用 adb shell input text 內容 直接把文字送進手機的輸入框,測試時很方便。

要把讀取流轉成圖片,用 BitmapFactory 即可,它能把檔案、串流、位元組陣列轉成 Bitmap:

Bitmap bitmap = BitmapFactory.decodeStream(InputStream in);

最後再用 imageView.setImageBitmap(bitmap); 把圖片設定上去。

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