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

Android 下載圖片並顯示:從基礎版到帶進度條的進階版

編輯:Android 開發實例

在 App 裡把網路圖片抓下來放到畫面上,是每個 Android 新手都會遇到的課題。以下從最直白的寫法出發,再逐步加上進度條,讓使用者體驗更完整。

一、最基礎的下載顯示

先在版面配置裡擺一個 ImageView 作為顯示容器:

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

    <ImageView android:src="@drawable/icon"
        android:layout_width="wrap_content"
        android:id="@+id/imgPic"
        android:layout_gravity="center|center_vertical"
        android:layout_height="fill_parent">
    </ImageView>

</LinearLayout>

接著在 Activity 中取得遠端圖片並塞進 ImageView:

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 = "圖片檔案位址";
        loadRmoteImage(url);
    }

    /**
     * @param imgUrl 遠端圖片檔案的 URL
     *                下載遠端圖片
     */
    private void loadRmoteImage(String imgUrl) {
        URL fileURL = null;
        Bitmap bitmap = null;
        try {
            fileURL = new URL(imgUrl);
        } catch (MalformedURLException err) {
            err.printStackTrace();
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) fileURL
                .openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            int length = (int) conn.getContentLength();
            if (length != -1) {
                byte[] imgData = new byte[length];
                byte[] buffer = new byte[512];
                int readLen = 0;
                int destPos = 0;
                while ((readLen = is.read(buffer)) > 0) {
                    System.arraycopy(buffer, 0, imgData, destPos, readLen);
                    destPos += readLen;
                }
                bitmap = BitmapFactory.decodeByteArray(imgData, 0,
                    imgData.length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        imgPic.setImageBitmap(bitmap);
    }
}

流程很單純:開一條 HttpURLConnection、讀進位元組陣列、用 BitmapFactory.decodeByteArray() 解成 Bitmap,最後 setImageBitmap() 上畫面。別忘了在 AndroidManifest.xml 加上 android.permission.INTERNET 權限。

二、加上進度條的改良版

網路慢或圖片大時,畫面會空白一大片,使用者往往以為程式當掉了。加一條 ProgressBar,讓等待變成看得見的過程,是提升體驗最划算的投資。同時也該把下載丟到子執行緒,避免阻塞主執行緒(UI Thread)而引發 ANR。

public class DownloadImage extends Activity {
    private ImageView imgPic;
    private ProgressBar progressBar;
    private int totalSize = 0;
    private int size = 0;
    private Handler mHandler;
    String url = "https://android.tgbus.com/Android/UploadFiles_4504/201107/20110729103701841.jpg";
    private Bitmap bitmap = null;

    @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);
        progressBar.setProgress(getProgressInt(progressBar.getMax()));
        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                progressBar.setProgress(getProgressInt(progressBar.getMax()));
                if (bitmap != null) {
                    imgPic.setImageBitmap(bitmap);
                }
            }
        };
        new Thread() {
            public void run() {
                loadRmoteImage(url);
            }
        }.start();
    }

    /**
     * @param imgUrl 遠端圖片檔案的 URL
     *                下載遠端圖片
     */
    private void loadRmoteImage(String imgUrl) {
        URL fileURL = null;
        try {
            fileURL = new URL(imgUrl);
        } catch (MalformedURLException err) {
            err.printStackTrace();
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) fileURL
                .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 = 0;
                int destPos = 0;
                while ((readLen = is.read(buffer)) > 0) {
                    System.arraycopy(buffer, 0, imgData, destPos, readLen);
                    destPos += readLen;
                    size = destPos;
                    mHandler.sendEmptyMessage(1);
                    Thread.sleep(100);
                }
                bitmap = BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
                mHandler.sendEmptyMessage(1);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

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

關鍵改動有三處:下載搬到子 Thread;用 Handler 把進度回傳主執行緒更新 ProgressBar(Android 不允許在子執行緒直接操作 UI);透過 size / totalSize 的比例換算成進度條刻度。

補充提醒:範例中的 Thread.sleep(100) 只是為了讓進度條看起來有層次感,正式專案裡請移除,它會拖慢下載速度。另外 conn.getContentLength() 有時會回傳 -1(伺服器未提供 Content-Length),此時進度條無法運作,需另外設計不確定型態的進度顯示。

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