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

Android 下載網路圖片並顯示:從 strings.xml 到 ImageView

編輯:關於 Android 程式設計

做一個「輸入網址、抓圖、顯示」的小工具,剛好把資源管理、版面配置與網路請求串在一起。以下按開發順序走一遍。

一、先把字串抽到 strings.xml

養成習慣,畫面上出現的文字不要寫死在版面檔裡。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">網絡圖片查看器</string>
    <string name="imgpath">輸入圖片地址:</string>
    <string name="getBtn">獲取圖片</string>
    <string name="error">獲取圖片失敗</string>
</resources>

二、版面配置

用垂直 LinearLayout 依序排下來:提示文字、輸入框、按鈕、顯示區。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:orientation="vertical"
    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" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/imgpath" />

    <EditText
        android:id="@+id/imgpathInput"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="text" />

    <Button
        android:id="@+id/getBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/getBtn" />

    <ImageView
        android:id="@+id/imgView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

三、程式碼

為了方便閱讀,這裡把網路方法都放在同一個類別。實務上建議把兩個 static 方法抽到工具類中,結構會清楚很多。

public class MainActivity extends Activity implements OnClickListener {

    private EditText pathText;
    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        pathText  = (EditText) findViewById(R.id.imgpathInput);
        imageView = (ImageView) findViewById(R.id.imgView);

        Button button = (Button) findViewById(R.id.getBtn);
        button.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onClick(View v) {
        String path = pathText.getText().toString();
        byte[] data = null;
        try {
            data = getImgData(path);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, R.string.error, Toast.LENGTH_SHORT).show();
            return;   // 取得失敗就不該繼續解碼
        }
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
        imageView.setImageBitmap(bitmap);
    }

    /** 抓取圖片並回傳位元組陣列 */
    public static byte[] getImgData(String path) throws Exception {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");

        if (conn.getResponseCode() == 200) {
            InputStream in = conn.getInputStream();
            return read(in);
        }
        Log.d("tong.getImg", "服務器無響應");
        return null;
    }

    /** 把輸入流讀進記憶體並轉為 byte[] */
    public static byte[] read(InputStream in) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[10240];
        int len = 0;
        while ((len = in.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        return outStream.toByteArray();
    }
}

四、權限別漏掉

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

五、這份範例在真實專案中的問題

上面這段程式碼能跑,但直接搬上線會遇到幾個麻煩,值得逐一說明。

網路請求寫在主執行緒。 從 Android 3.0(Honeycomb)開始,NetworkOnMainThreadException 會直接讓程式崩潰。必須改用背景執行緒,例如 AsyncTask、Kotlin 協程或 ExecutorService。

缺少例外處理的完整性。 getImgData() 可能回傳 null,而 BitmapFactory.decodeByteArray() 收到 null 會丟出 NullPointerException。原範例的 catch 區塊沒有 return,會帶著 null 繼續往下走。這類「失敗路徑沒走完」的問題在網路程式裡特別常見。

沒有連線關閉與 read timeout。 只設了 connectTimeout,還應加上 setReadTimeout(),並在 finally 中確實關閉串流,否則弱網環境下容易累積洩漏。

整張圖直接載入記憶體。 大圖會輕易觸發 OOM。正確做法是先讀取圖片邊界資訊決定縮放比例(inJustDecodeBounds + inSampleSize),再進行解碼。

重複按鈕會觸發多次請求。 應在請求期間停用按鈕或顯示進度指示。

若只是想完成「顯示網路圖片」這件事,成熟方案是直接用 Glide 或 Coil:一行 Glide.with(context).load(url).into(imageView) 就涵蓋了背景執行緒、快取、縮放、錯誤佔位圖與生命週期管理。上述手刻版本的價值在於理解底層發生了什麼——特別是當你遇到 OOM 或需要客製解碼流程時,這些知識就會派上用場。

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