Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 下載網路圖片並顯示:基礎版與帶進度條版

編輯:Android 開發實例

從網路下載圖片顯示在畫面上,是專案裡很常遇到的需求。這裡整理兩個版本:先是最基本的寫法,再補上進度條以改善等待時的使用者體驗。

兩個版本都需要在 AndroidManifest.xml 加上網路權限:<uses-permission android:name="android.permission.INTERNET" />。

一、基礎版

版面很簡單,一個置中的 ImageView:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imgPic"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_gravity="center|center_vertical"
        android:src="@drawable/icon" />
</LinearLayout>
public class DownloadImage extends Activity {

    private ImageView imgPic;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.download_image);
        imgPic = (ImageView) findViewById(R.id.imgPic);

        String url = "https://example.com/pic.jpg";
        loadRemoteImage(url);
    }

    /** 下載遠端圖片 */
    private Bitmap loadRemoteImage(String imgUrl) throws IOException {
        URL fileURL = new URL(imgUrl);
        HttpURLConnection conn = (HttpURLConnection) fileURL.openConnection();
        conn.setDoInput(true);
        conn.connect();

        InputStream is = conn.getInputStream();
        int length = (int) conn.getContentLength();
        if (length == -1) {
            return null;    // 拿不到長度就無法預先配置緩衝
        }

        byte[] imgData = new byte[length];
        byte[] buffer = new byte[512];
        int readLen, destPos = 0;
        while ((readLen = is.read(buffer)) > 0) {
            System.arraycopy(buffer, 0, imgData, destPos, readLen);
            destPos += readLen;
        }
        return BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
    }
}

這裡有個必須修正的問題:原範例直接在 onCreate 裡下載,而網路請求在 Android 3.0 之後被嚴格禁止在主執行緒執行,會直接拋出 NetworkOnMainThreadException。正確做法是把下載放到背景執行緒,完成後再切回主執行緒更新 UI——也就是下面第二個版本要做的事。

二、帶進度條的版本

網路慢或圖片大時,畫面會空白一片,使用者往往以為程式當掉了。加一條進度條,就能明確告知「正在進行中」。

public class DownloadImageWithProgress extends Activity {

    private ImageView imgPic;
    private ProgressBar progressBar;
    private Handler mHandler;
    private Bitmap bitmap = null;
    private int totalSize = 0;
    private int size = 0;

    private String url = "https://example.com/pic.jpg";

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

        imgPic = (ImageView) findViewById(R.id.imgPic);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);

        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                progressBar.setProgress(getProgressInt(progressBar.getMax()));
                if (bitmap != null) {
                    imgPic.setImageBitmap(bitmap);
                }
            }
        };

        new Thread() {
            public void run() {
                loadRemoteImage(url);
            }
        }.start();
    }

    private void loadRemoteImage(String imgUrl) {
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) new URL(imgUrl).openConnection();
            conn.setDoInput(true);
            conn.connect();

            InputStream is = conn.getInputStream();
            int length = (int) conn.getContentLength();
            totalSize = length;

            if (length != -1) {
                byte[] imgData = new byte[length];
                byte[] buffer = new byte[512];
                int readLen, destPos = 0;
                while ((readLen = is.read(buffer)) > 0) {
                    System.arraycopy(buffer, 0, imgData, destPos, readLen);
                    destPos += readLen;
                    size = destPos;
                    mHandler.sendEmptyMessage(1);   // 通知 UI 更新進度
                    Thread.sleep(100);
                }
                bitmap = BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
                mHandler.sendEmptyMessage(1);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

    private int getProgressInt(int max) {
        return (totalSize > 0) ? (int) (size * max * 1.0 / totalSize) : 0;
    }
}

[下載中效果圖]

[下載完成效果圖]

三、幾個實務上的建議

第一,Thread.sleep(100) 只是為了讓動畫看得清楚,正式環境請拿掉,改為降低發送訊息的頻率即可,否則會拖慢下載。

第二,圖片應該快取到本機,避免每次進入頁面都重新下載;同時要注意 ImageView 顯示大圖容易 OutOfMemoryError,實務上會先用 BitmapFactory.Options 的 inJustDecodeBounds 讀取尺寸,再按目標檢視大小做 inSampleSize 縮放。

第三,現行專案通常不會自己寫這一整套。成熟的做法是用 Glide、Picasso 或 Coil 這類圖片載入庫,下載、快取、解碼、縮放、生命週期管理與進度顯示都已處理好;上面這些程式碼的價值在於理解底層流程,以及在没有第三方套件可用時能自己動手。

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