Glide4圖片加載添加進(jìn)度

前言

最近在做一個(gè)Glide的工具類独郎,公司的項(xiàng)目里沒有cdn加載圖片很慢踩麦,想添加圖片加載進(jìn)度。找了一圈發(fā)現(xiàn)Glide本身并不提供進(jìn)度監(jiān)聽

添加依賴

    api 'com.github.bumptech.glide:glide:4.9.0'
    api 'com.github.bumptech.glide:okhttp3-integration:4.9.0'
    annotationProcessor 'com.github.bumptech.glide:annotations:4.9.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'

如果你已經(jīng)移植了andorid x

    api 'com.github.bumptech.glide:glide:4.9.0'
    api 'com.github.bumptech.glide:okhttp3-integration:4.9.0'
    //解決Glide找不到Android聲明庫(kù)問題
    annotationProcessor 'androidx.annotation:annotation:1.0.0' 
    annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'

注意 這里第三個(gè)依賴一定要使用annotationProcessor氓癌。

生成GlideApp

@GlideModule
public class HydraGlideModule extends AppGlideModule {
}

這里其實(shí)直接繼承AppGlideModule 添加@GlideModule谓谦,同步項(xiàng)目就可以生成GlideApp。

添加監(jiān)聽

關(guān)于添加進(jìn)度監(jiān)聽我就直接貼代碼了

OkHttpUrlLoader

public class OkHttpUrlLoader implements ModelLoader<GlideUrl, InputStream> {

    private final Call.Factory client;

    // Public API.
    @SuppressWarnings("WeakerAccess")
    public OkHttpUrlLoader(Call.Factory client) {
        this.client = client;
    }

    @Override
    public boolean handles(GlideUrl url) {
        return true;
    }

    @Override
    public LoadData<InputStream> buildLoadData(GlideUrl model, int width, int height,
                                               Options options) {
        return new LoadData<>(model, new OkHttpStreamFetcher(client, model));
    }

    /**
     * The default factory for {@link OkHttpUrlLoader}s.
     */
    // Public API.
    @SuppressWarnings("WeakerAccess")
    public static class Factory implements ModelLoaderFactory<GlideUrl, InputStream> {
        private static volatile Call.Factory internalClient;
        private final Call.Factory client;

        private static Call.Factory getInternalClient() {
            if (internalClient == null) {
                synchronized (Factory.class) {
                    if (internalClient == null) {
                        internalClient = new OkHttpClient();
                    }
                }
            }
            return internalClient;
        }

        /**
         * Constructor for a new Factory that runs requests using a static singleton client.
         */
        public Factory() {
            this(getInternalClient());
        }

        /**
         * Constructor for a new Factory that runs requests using given client.
         *
         * @param client this is typically an instance of {@code OkHttpClient}.
         */
        public Factory(Call.Factory client) {
            this.client = client;
        }

        @Override
        public ModelLoader<GlideUrl, InputStream> build(MultiModelLoaderFactory multiFactory) {
            return new OkHttpUrlLoader(client);
        }

        @Override
        public void teardown() {
            // Do nothing, this instance doesn't own the client.
        }
    }
}

OkHttpStreamFetcher

public class OkHttpStreamFetcher implements DataFetcher<InputStream>,
        okhttp3.Callback {
    private static final String TAG = "OkHttpFetcher";
    private final Call.Factory client;
    private final GlideUrl url;
    @SuppressWarnings("WeakerAccess")
    @Synthetic
    InputStream stream;
    @SuppressWarnings("WeakerAccess")
    @Synthetic
    ResponseBody responseBody;
    private volatile Call call;
    private DataCallback<? super InputStream> callback;

    // Public API.
    @SuppressWarnings("WeakerAccess")
    public OkHttpStreamFetcher(Call.Factory client, GlideUrl url) {
        this.client = client;
        this.url = url;
    }

    @Override
    public void loadData(Priority priority, final DataCallback<? super InputStream> callback) {
        Request.Builder requestBuilder = new Request.Builder().url(url.toStringUrl());
        for (Map.Entry<String, String> headerEntry : url.getHeaders().entrySet()) {
            String key = headerEntry.getKey();
            requestBuilder.addHeader(key, headerEntry.getValue());
        }
        Request request = requestBuilder.build();
        this.callback = callback;

        call = client.newCall(request);
        if (Build.VERSION.SDK_INT != Build.VERSION_CODES.O) {
            call.enqueue(this);
        } else {
            try {
                // Calling execute instead of enqueue is a workaround for #2355, where okhttp throws a
                // ClassCastException on O.
                onResponse(call, call.execute());
            } catch (IOException e) {
                onFailure(call, e);
            } catch (ClassCastException e) {
                // It's not clear that this catch is necessary, the error may only occur even on O if
                // enqueue is used.
                onFailure(call, new IOException("Workaround for framework bug on O", e));
            }
        }
    }

    @Override
    public void onFailure(@NonNull Call call, @NonNull IOException e) {
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "OkHttp failed to obtain result", e);
        }

        callback.onLoadFailed(e);
    }

    @Override
    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
        responseBody = response.body();
        if (response.isSuccessful()) {
            long contentLength = Preconditions.checkNotNull(responseBody).contentLength();
            stream = ContentLengthInputStream.obtain(responseBody.byteStream(), contentLength);
            callback.onDataReady(stream);
        } else {
            callback.onLoadFailed(new HttpException(response.message(), response.code()));
        }
    }

    @Override
    public void cleanup() {
        try {
            if (stream != null) {
                stream.close();
            }
        } catch (IOException e) {
            // Ignored
        }
        if (responseBody != null) {
            responseBody.close();
        }
        callback = null;
    }

    @Override
    public void cancel() {
        Call local = call;
        if (local != null) {
            local.cancel();
        }
    }

    @NonNull
    @Override
    public Class<InputStream> getDataClass() {
        return InputStream.class;
    }

    @NonNull
    @Override
    public DataSource getDataSource() {
        return DataSource.REMOTE;
    }
}

ProgressListener

public interface ProgressListener {

    /**
     * 圖片加載進(jìn)度回調(diào)
     *
     * @param isDone
     * @param progress
     */
    void onLoadProgress(boolean isDone, int progress);

    /**
     * 加載失敗
     */
    void onLoadFailed();
}

ProgressInterceptor 攔截器

public class ProgressInterceptor implements Interceptor {

    public static final Map<String, ProgressListener> LISTENER_MAP = new HashMap<>();

    public static void addListener(String url, ProgressListener listener) {
        LISTENER_MAP.put(url, listener);
    }


    public static void removeListener(String url) {
        LISTENER_MAP.remove(url);
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        String url = request.url().toString();
        ResponseBody body = response.body();
        Response newResponse =
                response.newBuilder().body(new ProgressResponseBody(url, body)).build();
        return newResponse;
    }
}

ProgressResponseBody 計(jì)算加載進(jìn)度贪婉,并在自定義的攔截器中使用

public class ProgressResponseBody extends ResponseBody {

    private BufferedSource bufferedSource;

    private ResponseBody responseBody;

    private ProgressListener listener;

    public ProgressResponseBody(String url, ResponseBody responseBody) {
        this.responseBody = responseBody;
        listener = ProgressInterceptor.LISTENER_MAP.get(url);
    }

    @Override
    public MediaType contentType() {
        return responseBody.contentType();
    }

    @Override
    public long contentLength() {
        return responseBody.contentLength();
    }

    @Override
    public BufferedSource source() {
        if (bufferedSource == null) {
            bufferedSource = Okio.buffer(new ProgressSource(responseBody.source()));
        }
        return bufferedSource;
    }

    private class ProgressSource extends ForwardingSource {

        long totalBytesRead = 0;

        int currentProgress;

        ProgressSource(Source source) {
            super(source);
        }

        @Override
        public long read(Buffer sink, long byteCount) throws IOException {
            long bytesRead = super.read(sink, byteCount);
            long fullLength = responseBody.contentLength();
            if (bytesRead == -1) {
                totalBytesRead = fullLength;
            } else {
                totalBytesRead += bytesRead;
            }
            int progress = (int) (100f * totalBytesRead / fullLength);
            if (listener != null && progress != currentProgress) {
                listener.onLoadProgress(progress == 100, progress);
            }
            if (listener != null && totalBytesRead == fullLength) {
                listener = null;
            }
            currentProgress = progress;
            return bytesRead;
        }
    }
}

在Glide中使用

@GlideModule
public class HydraGlideModule extends AppGlideModule {


    @Override
    public boolean isManifestParsingEnabled() {
        return super.isManifestParsingEnabled();
    }

    @Override
    public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) {
        super.applyOptions(context, builder);
    }

    @Override
    public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new ProgressInterceptor())
                .build();

        registry.replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(okHttpClient));
    }
}

具體使用

public void loadWhitListener(final Context context, final String url, final ImageView imageView,
                                 ProgressListener progressListener) {


        if (check(context, url, imageView)) {
            LogUtils.i("ImageUtils 傳入的參數(shù)錯(cuò)誤,請(qǐng)檢查!!!");
            return;
        }
        
        ProgressInterceptor.addListener(url, progressListener);

        GlideApp.with(context)
                .load(url)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .into(new DrawableImageViewTarget(imageView) {

                    @Override
                    public void onLoadStarted(@Nullable Drawable placeholder) {
                        super.onLoadStarted(placeholder);
                       imageView.setImageResource(R.color.color_646464);
                    }


                    @Override
                    public void onLoadFailed(@Nullable Drawable errorDrawable) {
                        super.onLoadFailed(errorDrawable);
                        ProgressInterceptor.LISTENER_MAP.get(url).onLoadFailed();
                        imageView.setImageResource(R.color.color_transparent);
                    }

                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<
                            ? super Drawable> transition) {
                        super.onResourceReady(resource, transition);

                        ProgressInterceptor.removeListener(url);

                    }
                });
    }

傳送門

相關(guān)資料

Android Glide4.0+圖片加載進(jìn)度監(jiān)聽
基于Glide V4.0封裝的GlideImageView反粥,可監(jiān)聽加載圖片時(shí)的進(jìn)度
實(shí)現(xiàn)帶進(jìn)度的Glide圖片加載功能(基于3.7)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市谓松,隨后出現(xiàn)的幾起案子星压,更是在濱河造成了極大的恐慌,老刑警劉巖鬼譬,帶你破解...
    沈念sama閱讀 216,324評(píng)論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件娜膘,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡优质,警方通過查閱死者的電腦和手機(jī)竣贪,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,356評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來巩螃,“玉大人演怎,你說我怎么就攤上這事”芊Γ” “怎么了爷耀?”我有些...
    開封第一講書人閱讀 162,328評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)拍皮。 經(jīng)常有香客問我歹叮,道長(zhǎng),這世上最難降的妖魔是什么铆帽? 我笑而不...
    開封第一講書人閱讀 58,147評(píng)論 1 292
  • 正文 為了忘掉前任咆耿,我火速辦了婚禮,結(jié)果婚禮上爹橱,老公的妹妹穿的比我還像新娘萨螺。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,160評(píng)論 6 388
  • 文/花漫 我一把揭開白布慰技。 她就那樣靜靜地躺著椭盏,像睡著了一般。 火紅的嫁衣襯著肌膚如雪惹盼。 梳的紋絲不亂的頭發(fā)上庸汗,一...
    開封第一講書人閱讀 51,115評(píng)論 1 296
  • 那天,我揣著相機(jī)與錄音手报,去河邊找鬼蚯舱。 笑死,一個(gè)胖子當(dāng)著我的面吹牛掩蛤,可吹牛的內(nèi)容都是我干的枉昏。 我是一名探鬼主播,決...
    沈念sama閱讀 40,025評(píng)論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼揍鸟,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼兄裂!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起阳藻,我...
    開封第一講書人閱讀 38,867評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤晰奖,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后腥泥,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體匾南,經(jīng)...
    沈念sama閱讀 45,307評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,528評(píng)論 2 332
  • 正文 我和宋清朗相戀三年蛔外,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了蛆楞。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,688評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡夹厌,死狀恐怖豹爹,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情矛纹,我是刑警寧澤臂聋,帶...
    沈念sama閱讀 35,409評(píng)論 5 343
  • 正文 年R本政府宣布,位于F島的核電站或南,受9級(jí)特大地震影響逻住,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜迎献,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,001評(píng)論 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望腻贰。 院中可真熱鬧吁恍,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,657評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至翼闽,卻和暖如春拾徙,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背感局。 一陣腳步聲響...
    開封第一講書人閱讀 32,811評(píng)論 1 268
  • 我被黑心中介騙來泰國(guó)打工尼啡, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人询微。 一個(gè)月前我還...
    沈念sama閱讀 47,685評(píng)論 2 368
  • 正文 我出身青樓崖瞭,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親撑毛。 傳聞我的和親對(duì)象是個(gè)殘疾皇子书聚,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,573評(píng)論 2 353