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

Android 開發(13):用 HTTP 把網路圖片抓回來,顯示在 ImageView 上

編輯:關於 Android 程式設計

App 想顯示一張不在手機裡、而是放在伺服器上的圖片,本質上就是兩件事:把圖片的位元組從網路讀回來,再交給 ImageView 去解碼。這篇文章把整個流程拆成「畫面配置 → 網路工具類 → 串流工具類 → 網路狀態檢查 → 權限宣告」五個部分,順便說明幾個實務上一定會踩到的坑。

一、先把畫面搭起來

版面用 RelativeLayout 就足夠:一個輸入網址的 EditText、一個觸發下載的 Button,還有一個用來呈現結果的 ImageView。ImageView 的 src 先放一張 ic_launcher 當佔位圖,這樣在圖片還沒下載回來之前,使用者至少看得到一個框。

<RelativeLayout 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: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/url_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:ems="10"
        android:inputType="textPostalAddress"
        android:text="@string/url_text" >
        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/btn_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/url_text"
        android:layout_below="@+id/url_text"
        android:layout_marginTop="32dp"
        android:onClick="sendHttp"
        android:text="@string/btn_text" />

    <ImageView
        android:id="@+id/iv_ie"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/url_text"
        android:layout_below="@+id/btn_text"
        android:src="@drawable/ic_launcher" />

</RelativeLayout>

幾個細節值得留意:android:onClick="sendHttp" 表示 Activity 裡必須有一個方法簽名為 public void sendHttp(View v) 的函式;inputType="textPostalAddress" 只是順手讓輸入法鍵盤排出斜線與冒號,方便打網址;ems="10" 控制的是顯示寬度。

二、HttpUtils:把 GET 請求封裝起來

同一個專案裡往往會需要「抓一段文字」和「抓一張圖」兩種能力,所以把 HttpURLConnection 的細節收進同一個工具類,對外只暴露兩個方法:一個回傳字串,一個回傳 Bitmap。

package com.example.lession08_code.utis;

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

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class HttpUtils {

    /** 抓取網頁內容,回傳字串 */
    public static String sendGet(String path) {
        String content = null;
        try {
            URL url = new URL(path);                                  // 設定要訪問的位址
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");                             // 請求方法
            conn.setConnectTimeout(5000);                             // 連線逾時 5 秒
            if (conn.getResponseCode() == 200) {                      // 伺服器有正常回應
                InputStream is = conn.getInputStream();
                byte[] data = StreamTools.isTodata(is);               // 串流轉位元組
                content = new String(data);
                if (content.contains("gb2312")) {                     // 依內容判斷編碼
                    content = new String(data, "gb2312");
                }
            }
            conn.disconnect();                                        // 記得斷線
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

    /** 抓取網路圖片,直接解碼成 Bitmap */
    public static Bitmap sendGets(String path) {
        Bitmap bitmap = null;
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            if (conn.getResponseCode() == 200) {
                InputStream is = conn.getInputStream();
                bitmap = BitmapFactory.decodeStream(is);              // 串流直接轉 Bitmap
            }
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }
}

圖片之所以不需要自己組位元組陣列,是因為 BitmapFactory.decodeStream() 已經把「讀串流 → 解析圖片格式 → 產生 Bitmap」這一切做完了。文字就不行,編碼得自己處理,這也是為什麼 sendGet 裡多了一段 gb2312 的判斷。

三、StreamTools:把串流讀成位元組陣列

讀串流最直觀的寫法就是「準備一個緩衝區,反覆 read,直到回傳 -1」,再把過程中寫入的資料一次取出。

package com.example.lession08_code.utis;

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

public class StreamTools {

    public static byte[] isTodata(InputStream is) throws IOException {
        ByteArrayOutputStream bops = new ByteArrayOutputStream(); // 位元組輸出流
        byte[] buffer = new byte[1024];                           // 讀取用的緩衝區
        int len = 0;
        while ((len = is.read(buffer)) != -1) {                   // -1 代表讀到底
            bops.write(buffer, 0, len);                           // 只寫入實際讀到的長度
        }
        return bops.toByteArray();
    }
}

這裡最容易犯的錯是寫成 bops.write(buffer),那會把緩衝區尾端沒被填滿的 0 一起寫進去,檔案就會多出一堆無效位元組。

四、NetWorkUtils:先確認網路通不通

還沒連線就發現沒有網路,直接丟例外給使用者看是很糟的體驗。比較友善的做法是跳出提示框,讓使用者選擇要不要去系統設定開網路。

package com.example.lession08_code.utis;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.Toast;

public class NetWorkUtils {

    private Context context;
    public ConnectivityManager connectivityManager;

    public NetWorkUtils(Context context) {
        this.context = context;
        // 取得系統的網路連線服務
        connectivityManager = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
    }

    /** 有可用網路回傳 true,否則跳提示框並回傳 false */
    public boolean setActiveNetWork() {
        boolean flag = false;
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo == null) {
            new AlertDialog.Builder(context)
                    .setTitle("網路不可用")
                    .setMessage("要前往設定開啟網路嗎?")
                    .setPositiveButton("確認", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Toast.makeText(context, "點擊確認", Toast.LENGTH_LONG).show();
                            Intent intent = new Intent();
                            intent.setAction(Intent.ACTION_MAIN);
                            intent.addCategory("android.intent.category.LAUNCHER");
                            intent.setComponent(new ComponentName(
                                    "com.android.settings",
                                    "com.android.settings.Settings"));
                            intent.setFlags(0x10200000);
                            context.startActivity(intent);            // 直接跳設定頁
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) { }
                    })
                    .show();                                          // 少了 show() 什麼都不會出現
        }
        if (networkInfo != null) {
            flag = true;
        }
        return flag;
    }
}

兩個實務提醒:Dialog 一定要呼叫 show() 才會顯示,少了這行是新手最常遇到的「為什麼沒反應」;另外,從非 Activity 的 Context 彈 Dialog 在較新的 Android 版本上會失敗,所以這個類通常會傳入 Activity 本身。

五、別忘了權限

網路相關的權限必須寫在 AndroidManifest.xml 的 <manifest> 節點下:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>

少了 INTERNET,請求會在執行期直接爆炸;少了 ACCESS_NETWORK_STATE,getActiveNetworkInfo() 永遠回傳 null,也就是永遠判定為沒有網路。

六、串起來:主線程不能做網路請求

最後把流程接上:使用者點 Button → 開一條子執行緒去呼叫 HttpUtils.sendGets() → 拿到 Bitmap 後透過 Handler 把結果送回主執行緒 → 在 handleMessage() 裡呼叫 imageView.setImageBitmap(bitmap)。

這一步是整篇文章最關鍵的觀念:從 Android 3.0(Honeycomb)開始,在主執行緒發起網路請求會直接丟出 NetworkOnMainThreadException;即使僥倖沒拋例外,長時間的 I/O 也會讓畫面卡住,最終觸發 ANR。所以「網路一定在子執行緒、UI 一定在主執行緒更新」不是建議,而是硬性規則。子執行緒怎麼和主執行緒溝通,可以參考上一篇講的 Handler 機制。

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