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

Android 加載網絡 GIF 完整解決方案:緩存、進度與同步一次搞定

編輯:關於 Android 程式設計

前言

加載並顯示 GIF 是 App 中很常見的需求。像加載普通圖片一樣,一個完善的方案大致要滿足以下幾點:

1、自動將 GIF 下載到本地作為緩存,同一 url 第二次加載無需重複下載;

2、由於 GIF 往往體積較大,需要用圓形進度條提示下載進度;

3、在 GIF 完全下載前,先顯示第一幀作為佔位,下載完成後再自動播放動畫;

4、兩個不同頁面加載同一張 GIF 時,加載進度應保持一致;

5、支持 ViewPager 同時加載多個 GIF 動圖。

效果演示:

實現思路

1、關於下載與磁盤緩存:這裡使用 HttpURLConnection 根據 url 下載,下載前先將 url 字符串用 16 位 MD5 轉換作為文件名,再以 4096 字節為單位,通過緩衝流邊讀邊寫,防止內存溢出。而不斷向磁盤寫入也正好幫助實現了「第一幀佔位」的效果。

2、關於進度指示:這裡用一個圓形第三方 ProgressBar 加一個 TextView 來實現。由於下載以 4096 字節為緩衝,每讀取一次就更新一次進度 UI。文件總大小由 http 響應頭部的 Content-Length 提供,用已下載大小除以它即可算出百分比。

3、關於不同頁面的下載同步:用戶在首頁看到一張 GIF,點擊後跳轉到大圖頁繼續下載,此時首頁的進度要帶到大圖頁,既不能讓用戶重複下載,也不能在大圖頁打開一張只下載了一半的圖。

解決辦法:下載開始前先建立一個 MD5.tmp 文件存儲內容,下載完成後再去掉 .tmp 後綴。這樣在文件系統中檢索某張 GIF 是否已下載時,未完成的圖片不會被誤檢索出來。

若某個 url 已開啟下載,此時又有新的下載請求指向同一 url,就用 WeakReference 把請求的 imageView、textView 和 progressBar 弱引用起來防止內存洩漏,再把它們加入一個 HashMap。該 HashMap 的 key 是 url,value 是這些控件弱引用組成的 list。下載線程更新進度或完成時,會根據 url 取出所有關聯控件統一刷新狀態,從而保證不同頁面進度一致,也避免重複下載。

4、關於用 GIF 第一幀佔位:GIF 顯示採用了 GitHub 上的開源項目 android-gif-drawable(https://github.com/koral--/android-gif-drawable)。該框架內部用 C 語言編寫了高效的執行代碼,可直接根據輸入流加載,也就是說不必等文件完全下載就能顯示已下載的內容,甚至可以像瀏覽器那樣逐行像素加載,十分好用。只需把尚未下載完的文件傳給 Drawable 顯示即可,並在之前判斷能否取到第一幀,然後把播放選項設為暫停。

5、關於 ViewPager 的使用:在 ViewPager 的 Adapter 中踩了不少坑,主要是緩存機制引起的顯示重複、無控件顯示等問題。要讓 GifImageView 和普通 ImageView 在 ViewPager 中和平共處,需先研究清楚其緩存機制。這裡的做法是:先根據圖片數量生成同等數量的 imageView 放進數組,ViewPager 切到哪張就從數組取出哪張放入 Container。GifImageView 同理,只是放在另一個數組裡,根據 position 取對應的 GifImageView 再 add 進 container,對已 add 過的會報異常,用 catch 處理即可。

具體代碼

加載工具類:

import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import com.imaginato.qravedconsumer.task.AlxMultiTask;
import com.lidroid.xutils.HttpUtils;
import com.pnikosis.materialishprogress.ProgressWheel;
import com.qraved.app.R;
import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;
import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;

/**
 * Created by Alex on 2016/6/16.
 */
public class AlxGifHelper {
    public static class ProgressViews {
        public ProgressViews(WeakReference gifImageViewWeakReference,
                WeakReference progressWheelWeakReference,
                WeakReference textViewWeakReference, int displayWidth) {
            this.gifImageViewWeakReference = gifImageViewWeakReference;
            this.progressWheelWeakReference = progressWheelWeakReference;
            this.textViewWeakReference = textViewWeakReference;
            this.displayWidth = displayWidth;
        }
        public WeakReference gifImageViewWeakReference; // gif 顯示控件
        public WeakReference progressWheelWeakReference; // 圓形進度條
        public WeakReference textViewWeakReference; // 顯示當前進度的文本框
        public int displayWidth; // imageView 的控件寬度
    }

    // 防止同一個 gif 建立多個下載線程,url 和 imageView 是一對多關係,均使用弱引用防止內存洩漏
    public static ConcurrentHashMap> memoryCache;

    /**
     * 通過本地緩存或聯網加載一張 GIF 圖片
     */
    public static void displayImage(final String url, GifImageView gifView, ProgressWheel progressBar,
            TextView tvProgress, int displayWidth) {
        // 首先查詢這個 gif 是否已被緩存
        String md5Url = getMd5(url);
        String path = gifView.getContext().getCacheDir().getAbsolutePath() + "/" + md5Url;
        final File cacheFile = new File(path);
        if (cacheFile.exists()) {
            if (displayImage(cacheFile, gifView, displayWidth)) {
                if (progressBar != null) progressBar.setVisibility(View.GONE);
                if (tvProgress != null) tvProgress.setVisibility(View.GONE);
                return;
            }
        }
        // 使用弱引用防止 activity finish 後 gif 未加載完成導致內存洩漏
        final WeakReference imageViewWait = new WeakReference(gifView);
        final WeakReference progressBarWait = new WeakReference(progressBar);
        final WeakReference textViewWait = new WeakReference(tvProgress);
        if (gifView.getId() != R.id.gif_photo_view) gifView.setImageResource(R.drawable.qraved_bg_default);
        if (memoryCache != null && memoryCache.get(url) != null) {
            memoryCache.get(url).add(new ProgressViews(imageViewWait, progressBarWait, textViewWait, displayWidth));
            return;
        }
        if (memoryCache == null) memoryCache = new ConcurrentHashMap<>();
        if (memoryCache.get(url) == null) memoryCache.put(url, new ArrayList());
        memoryCache.get(url).add(new ProgressViews(imageViewWait, progressBarWait, textViewWait, displayWidth));

        final HttpUtils http = new HttpUtils();
        startDownLoad(url, new File(cacheFile.getAbsolutePath() + ".tmp"), new DownLoadTask() {
            @Override
            public void onStart() {
                ProgressWheel progressBar = progressBarWait.get();
                TextView tvProgress = textViewWait.get();
                if (progressBar != null) {
                    progressBar.setVisibility(View.VISIBLE);
                    progressBar.setProgress(0);
                    if (tvProgress == null) return;
                    tvProgress.setVisibility(View.VISIBLE);
                    tvProgress.setText("1%");
                }
            }

            @Override
            public void onLoading(long total, long current) {
                int progress = 0;
                if (total > 0) progress = (int) (current * 100 / total);
                ArrayList viewses = memoryCache.get(url);
                if (viewses == null) return;
                for (ProgressViews vs : viewses) {
                    ProgressWheel progressBar = vs.progressWheelWeakReference.get();
                    if (progressBar != null) {
                        progressBar.setProgress((float) progress / 100f);
                        if (total == -1) progressBar.setProgress(20);
                    }
                    TextView tvProgress = vs.textViewWeakReference.get();
                    if (tvProgress != null) tvProgress.setText(progress + "%");
                }
                getFirstPicOfGIF(new File(cacheFile.getAbsolutePath() + ".tmp"), vs.gifImageViewWeakReference.get());
            }

            public void onSuccess(File file) {
                if (file == null) return;
                String path = file.getAbsolutePath();
                if (path == null || path.length() < 5) return;
                File downloadFile = new File(path);
                File renameFile = new File(path.substring(0, path.length() - 4));
                if (path.endsWith(".tmp")) downloadFile.renameTo(renameFile);
                if (memoryCache == null) return;
                ArrayList viewArr = memoryCache.get(url);
                if (viewArr == null || viewArr.size() == 0) return;
                for (ProgressViews ws : viewArr) {
                    GifImageView gifImageView = ws.gifImageViewWeakReference.get();
                    if (gifImageView != null) displayImage(renameFile, gifImageView, ws.displayWidth);
                    TextView tvProgress = ws.textViewWeakReference.get();
                    ProgressWheel progressBar = ws.progressWheelWeakReference.get();
                    if (progressBar != null) progressBar.setVisibility(View.GONE);
                    if (tvProgress != null) tvProgress.setVisibility(View.GONE);
                }
                memoryCache.remove(url);
            }

            @Override
            public void onFailure(Throwable e) {
                TextView tvProgress = textViewWait.get();
                ProgressWheel progressBar = progressBarWait.get();
                if (progressBar != null) progressBar.setVisibility(View.GONE);
                if (tvProgress != null) tvProgress.setText("image download failed");
                if (memoryCache != null) memoryCache.remove(url);
            }
        });
    }

    /**
     * 通過本地文件顯示 GIF 文件
     */
    public static boolean displayImage(File localFile, GifImageView gifImageView, int displayWidth) {
        if (localFile == null || gifImageView == null) return false;
        GifDrawable gifFrom;
        try {
            gifFrom = new GifDrawable(localFile);
            int raw_height = gifFrom.getIntrinsicHeight();
            int raw_width = gifFrom.getIntrinsicWidth();
            if (gifImageView.getScaleType() != ImageView.ScaleType.CENTER_CROP
                    && gifImageView.getScaleType() != ImageView.ScaleType.FIT_XY) {
                if (raw_width < 1 || raw_height < 1) return false;
                int imageViewWidth = displayWidth;
                if (imageViewWidth < 1) imageViewWidth = raw_width;
                int imageViewHeight = imageViewWidth * raw_height / raw_width;
                ViewGroup.LayoutParams params = gifImageView.getLayoutParams();
                if (params != null) {
                    params.height = imageViewHeight;
                    params.width = imageViewWidth;
                }
            }
            gifImageView.setImageDrawable(gifFrom);
            return true;
        } catch (IOException e) {
            return false;
        }
    }

    /**
     * 獲取一個 String 的 md5 值(取 16 位以提高磁盤查找速度)
     */
    public static String getMd5(String str) {
        if (str == null || str.length() < 1) return "no_image.gif";
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bs = md5.digest(str.getBytes());
            StringBuilder sb = new StringBuilder(40);
            for (byte x : bs) {
                if ((x & 0xff) >> 4 == 0) {
                    sb.append("0").append(Integer.toHexString(x & 0xff));
                } else {
                    sb.append(Integer.toHexString(x & 0xff));
                }
            }
            if (sb.length() < 24) return sb.toString();
            return sb.toString().substring(8, 24);
        } catch (NoSuchAlgorithmException e) {
            return "no_image.gif";
        }
    }

    public static abstract class DownLoadTask {
        abstract void onStart();
        abstract void onLoading(long total, long current);
        abstract void onSuccess(File target);
        abstract void onFailure(Throwable e);
        boolean isCanceled;
    }

    /**
     * 開啟下載任務到線程池,防止多並發線程過多
     */
    public static void startDownLoad(final String uri, final File targetFile, final DownLoadTask task) {
        final Handler handler = new Handler();
        new AlxMultiTask() {
            @Override
            protected Void doInBackground(Void... params) {
                task.onStart();
                downloadToStream(uri, targetFile, task, handler);
                return null;
            }
        }.executeDependSDK();
    }

    /**
     * 通過 HttpURLConnection 下載文件,使用普通 IO 讀寫
     */
    public static long downloadToStream(String uri, final File targetFile, final DownLoadTask task, Handler handler) {
        if (task == null || task.isCanceled) return -1;
        HttpURLConnection httpURLConnection = null;
        BufferedInputStream bis = null;
        OutputStream outputStream = null;
        long result = -1;
        long fileLen = 0;
        long currCount = 0;
        try {
            try {
                final URL url = new URL(uri);
                outputStream = new FileOutputStream(targetFile);
                httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setConnectTimeout(20000);
                httpURLConnection.setReadTimeout(10000);
                final int responseCode = httpURLConnection.getResponseCode();
                if (HttpURLConnection.HTTP_OK == responseCode) {
                    bis = new BufferedInputStream(httpURLConnection.getInputStream());
                    result = httpURLConnection.getExpiration();
                    result = result < System.currentTimeMillis() ? System.currentTimeMillis() + 40000 : result;
                    fileLen = httpURLConnection.getContentLength();
                } else {
                    return -1;
                }
            } catch (final Exception ex) {
                handler.post(new Runnable() {
                    @Override public void run() { task.onFailure(ex); }
                });
                return -1;
            }
            if (task.isCanceled) return -1;
            byte[] buffer = new byte[4096];
            int len = 0;
            BufferedOutputStream out = new BufferedOutputStream(outputStream);
            while ((len = bis.read(buffer)) != -1) {
                out.write(buffer, 0, len);
                currCount += len;
                if (task.isCanceled) return -1;
                final long finalFileLen = fileLen;
                final long finalCurrCount = currCount;
                handler.post(new Runnable() {
                    @Override public void run() { task.onLoading(finalFileLen, finalCurrCount); }
                });
            }
            out.flush();
            handler.post(new Runnable() {
                @Override public void run() { task.onSuccess(targetFile); }
            });
        } catch (Throwable e) {
            result = -1;
            task.onFailure(e);
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (final Throwable e) {
                    handler.post(new Runnable() {
                        @Override public void run() { task.onFailure(e); }
                    });
                }
            }
        }
        return result;
    }

    /**
     * 加載 gif 的第一幀圖像,用於下載完成前佔位
     */
    public static void getFirstPicOfGIF(File gifFile, GifImageView imageView) {
        if (imageView == null) return;
        if (imageView.getTag(R.style.AppTheme) instanceof Integer) return;
        try {
            GifDrawable gifFromFile = new GifDrawable(gifFile);
            boolean canSeekForward = gifFromFile.canSeekForward();
            if (!canSeekForward) return;
            gifFromFile.seekToFrame(0);
            gifFromFile.pause();
            imageView.setImageDrawable(gifFromFile);
            imageView.setTag(R.style.AppTheme, 1);
        } catch (IOException e) {
        }
    }
}

線程池:

import android.os.AsyncTask;
import android.os.Build;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 用於替換系統自帶的 AsyncTask,使用自定義線程池執行較複雜的工作
 */
public abstract class AlxMultiTask extends AsyncTask {
    private static ExecutorService photosThreadPool;
    private final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    private final int CORE_POOL_SIZE = CPU_COUNT + 1;

    public void executeDependSDK(Params... params) {
        if (photosThreadPool == null) photosThreadPool = Executors.newFixedThreadPool(CORE_POOL_SIZE);
        if (Build.VERSION.SDK_INT < 11) super.execute(params);
        else super.executeOnExecutor(photosThreadPool, params);
    }
}

ViewPager Adapter 的寫法(截取):

public class PhotoImageViewPageAdapter extends PagerAdapter {
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        String imageUrl = "https://xxx.com/sdf/xxx.gif";
        if (imageUrl.endsWith(".gif")) {
            View rl_gif = LayoutInflater.from(activity).inflate(R.layout.layout_photo_loading_gif_imageview, null);
            GifImageView gifImageView = (GifImageView) rl_gif.findViewById(R.id.gif_photo_view);
            ProgressWheel progressWheel = (ProgressWheel) rl_gif.findViewById(R.id.progress_wheel);
            CustomTextView tv_progress = (CustomTextView) rl_gif.findViewById(R.id.tv_progress);
            AlxGifHelper.displayImage(imageUrl, gifImageView, progressWheel, tv_progress, 0);
            try {
                container.addView(rl_gif);
            } catch (Exception e) {
            }
            return rl_gif;
        }
        return container;
    }
}

布局文件:

 

    
    
    

中間的 ProgressBar 使用了第三方庫:

dependencies {
    compile 'com.pnikosis:materialish-progress:1.7'
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved