android替换Glide通讯组件为Okhttp并监控加载进度

import com.bumptech.glide.GlideBuilder;

import com.bumptech.glide.load.DecodeFormat;

import com.bumptech.glide.load.engine.cache.ExternalCacheDiskCacheFactory;

import com.bumptech.glide.load.model.GlideUrl;

import com.bumptech.glide.module.GlideModule;

import java.io.InputStream;

import okhttp3.OkHttpClient;

import tsou.cn.glidetest.Glide.okhttp.OkHttpGlideUrlLoader;

import tsou.cn.glidetest.Glide.okhttp.ProgressInterceptor;

/**

  • 自定义模块

  • 目前Glide还无法识别我们自定义的MyGlideModule,

  • 如果想要让它生效,

  • 还得在AndroidManifest.xml文件当中加入如下配置才行

*/

public class MyGlideModule implements GlideModule {

/**

  • setMemoryCache()

  • 用于配置Glide的内存缓存策略,默认配置是LruResourceCache。

  • setBitmapPool()

  • 用于配置Glide的Bitmap缓存池,默认配置是LruBitmapPool。

  • setDiskCache()

  • 用于配置Glide的硬盘缓存策略,默认配置是InternalCacheDiskCacheFactory。

  • setDiskCacheService()

  • 用于配置Glide读取缓存中图片的异步执行器,默认配置是FifoPriorityThreadPoolExecutor,

  • 也就是先入先出原则。

  • setResizeService()

  • 用于配置Glide读取非缓存中图片的异步执行器,默认配置也是FifoPriorityThreadPoolExecutor。

  • setDecodeFormat()

  • 用于配置Glide加载图片的解码模式,默认配置是RGB_565。

*/

public static final int DISK_CACHE_SIZE = 500 * 1024 * 1024;

public static final String DISK_CACHE_NAME = “huangxiaoguo”;

@Override

public void applyOptions(Context context, GlideBuilder builder) {

/**

将所有Glide加载的图片缓存到SD卡上,

默认硬盘缓存大小都是250M,这里改为500

  • */

//builder.setDiskCache(new ExternalCacheDiskCacheFactory(context));

/**

ExternalCacheDiskCacheFactory的默认缓存路径

是在sdcard/Android/data/包名/cache/image_manager_disk_cache目录当中

*/

//builder.setDiskCache(new ExternalCacheDiskCacheFactory(context, DISK_CACHE_SIZE));

/**

  • 更改缓存最总文件夹名称

  • 是在sdcard/Android/data/包名/cache/DISK_CACHE_NAME目录当中

*/

builder.setDiskCache(new ExternalCacheDiskCacheFactory(context, DISK_CACHE_NAME, DISK_CACHE_SIZE));

/**

  • Glide也能使用ARGB_8888的图片格式

  • 虽然图片质量变好了,但同时内存开销也会明显增大

*/

builder.setDecodeFormat(DecodeFormat.PREFER_ARGB_8888);

}

@Override

public void registerComponents(Context context, Glide glide) {

/**

  • 不带拦截功能,只是单纯替换通讯组件

*/

//glide.register(GlideUrl.class, InputStream.class, new OkHttpGlideUrlLoader.Factory());

OkHttpClient.Builder builder = new OkHttpClient.Builder();

builder.addInterceptor(new ProgressInterceptor());

OkHttpClient okHttpClient = builder.build();

glide.register(GlideUrl.class, InputStream.class, new OkHttpGlideUrlLoader.Factory(okHttpClient));

}

}

记得在androidManifest.xml中配置

<meta-data

android:name=“tsou.cn.glidetest.Glide.MyGlideModule”

android:value=“GlideModule” />

这里面我将Glide缓存路径更改为SD卡等配置

详细请看我的另一篇博客:http://blog.csdn.net/huangxiaoguo1/article/details/78583146

定义下载回调


package tsou.cn.glidetest.Glide.okhttp;

/**

  • 下载回调

*/

public interface ProgressListener {

void onProgress(int progress);

}

自定义拦截器:


package tsou.cn.glidetest.Glide.okhttp;

import java.io.IOException;

import java.util.HashMap;

import java.util.Map;

import okhttp3.Interceptor;

import okhttp3.Request;

import okhttp3.Response;

import okhttp3.ResponseBody;

/**

  • 拦截器

*/

public class ProgressInterceptor implements Interceptor {

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;

}

}

监听下载进度的逻辑


package tsou.cn.glidetest.Glide.okhttp;

import android.util.Log;

import java.io.IOException;

import okhttp3.MediaType;

import okhttp3.ResponseBody;

import okio.Buffer;

import okio.BufferedSource;

import okio.ForwardingSource;

import okio.Okio;

import okio.Source;

/**

  • 监听下载进度的逻辑

*/

public class ProgressResponseBody extends ResponseBody {

private static final String TAG = “ProgressResponseBody”;

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);

Log.d(TAG, "download progress is " + progress);

if (listener != null && progress != currentProgress) {

listener.onProgress(progress);

}

if (listener != null && totalBytesRead == fullLength) {

listener = null;

}

currentProgress = progress;

return bytesRead;

}

}

}

布局

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android=“http://schemas.android.com/apk/res/android”

xmlns:tools=“http://schemas.android.com/tools”

android:layout_width=“match_parent”

android:layout_height=“match_parent”

tools:context=“tsou.cn.glidetest.ListActivity”>

<android.support.v4.widget.SwipeRefreshLayout

android:id=“@+id/swipe_refresh”

android:layout_width=“match_parent”

android:layout_height=“match_parent”>

<android.support.v7.widget.RecyclerView

android:id=“@+id/recyclerview”

android:layout_width=“match_parent”

android:layout_height=“match_parent” />

</android.support.v4.widget.SwipeRefreshLayout>

使用的Adapter


package tsou.cn.glidetest.adapter;

import android.support.annotation.Nullable;

import android.widget.ImageView;

import android.widget.ProgressBar;

import com.chad.library.adapter.base.BaseQuickAdapter;

import com.chad.library.adapter.base.BaseViewHolder;

import java.util.List;

import java.util.Locale;

import tsou.cn.glidetest.R;

import tsou.cn.glidetest.Util.ImageLoadUtil;

import tsou.cn.glidetest.bean.ListBean;

import tsou.cn.glidetest.view.RoundProgressBar;

/**

  • Created by Administrator on 2017/11/13 0013.

*/

public class ListAdapter extends BaseQuickAdapter<ListBean, BaseViewHolder> {

public ListAdapter(@Nullable List data) {

super(R.layout.item_list, data);

}

@Override

protected void convert(BaseViewHolder helper, ListBean item) {

ImageLoadUtil.display((ImageView) helper.getView(R.id.iv_list_home_photo),

(RoundProgressBar) helper.getView(R.id.round_progressbar), item.getImage());

helper.setText(R.id.tv_list_home_title, item.getTitle());

helper.setText(R.id.tv_list_home_source,

String.format(Locale.getDefault(), mContext.getString(R.string.source), item.getSource()));

helper.setText(R.id.tv_list_home_focus,

String.format(Locale.getDefault(), “%d”, item.getStar()));

helper.setText(R.id.tv_list_home_comments,

String.format(Locale.getDefault(), “%d”, item.getEvn()));

}

}

adapter中的条目布局


<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android=“http://schemas.android.com/apk/res/android”

xmlns:android_custom=“http://schemas.android.com/apk/res-auto”

xmlns:app=“http://schemas.android.com/apk/res-auto”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”>

<android.support.v7.widget.CardView

android:id=“@+id/cardview”

android:layout_width=“135dp”

android:layout_height=“90dp”

android:layout_marginLeft=“10px”

android:layout_marginRight=“40px”

android:layout_marginTop=“30px”

android:foreground=“?attr/selectableItemBackground”

app:cardBackgroundColor=“@android:color/white”

app:cardCornerRadius=“20px”

app:cardElevation=“10px”

app:cardPreventCornerOverlap=“false”

app:cardUseCompatPadding=“true”

app:contentPadding=“0px”>

<RelativeLayout

android:layout_width=“match_parent”

android:layout_height=“match_parent”>

<ImageView

android:id=“@+id/iv_list_home_photo”

android:layout_width=“match_parent”

android:layout_height=“match_parent”

android:scaleType=“fitXY” />

<tsou.cn.glidetest.view.RoundProgressBar

android:id=“@+id/round_progressbar”

android:layout_width=“55dip”

android:layout_height=“55dip”

android:layout_centerInParent=“true”

android_custom:progress=“1”

android_custom:roundColor=“#D1D1D1”

android_custom:roundProgressColor=“#3F51B5”

android_custom:roundWidth=“5dip”

android_custom:textColor=“#3F51B5”

android_custom:textSize=“12sp” />

</android.support.v7.widget.CardView>

<TextView

android:id=“@+id/tv_list_home_title”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:layout_alignTop=“@id/cardview”

android:layout_marginRight=“20px”

android:layout_toRightOf=“@id/cardview”

android:ellipsize=“end”

android:lineSpacingMultiplier=“1.2”

android:maxLines=“2”

android:paddingTop=“15px”

android:text=“@string/app_name”

android:textColor=“@android:color/black”

android:textSize=“14sp” />

<RelativeLayout

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:layout_alignBottom=“@id/cardview”

android:layout_alignLeft=“@id/tv_list_home_title”

android:layout_marginRight=“20px”>

<TextView

android:id=“@+id/tv_list_home_comments”

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”

android:layout_alignParentRight=“true”

android:drawableLeft=“@mipmap/icon_comments”

android:drawablePadding=“12px”

android:text=“%d”

android:textColor=“@android:color/darker_gray”

android:textSize=“12sp” />

<TextView

android:id=“@+id/tv_list_home_focus”

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”

android:layout_marginRight=“25px”

android:layout_toLeftOf=“@id/tv_list_home_comments”

android:drawableLeft=“@mipmap/icon_star”

android:drawablePadding=“12px”

android:text=“%d”

android:textColor=“@android:color/darker_gray”

android:textSize=“12sp” />

<TextView

android:id=“@+id/tv_list_home_source”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:layout_marginBottom=“25px”

android:layout_marginRight=“10px”

android:layout_toLeftOf=“@id/tv_list_home_focus”

android:singleLine=“true”

android:text=“@string/source”

android:textColor=“@android:color/darker_gray”

android:textSize=“12sp” />

主页面代码逻辑


package tsou.cn.glidetest;

import android.os.AsyncTask;

import android.os.Bundle;

import android.os.SystemClock;

import android.support.v4.widget.SwipeRefreshLayout;

import android.support.v7.app.AppCompatActivity;

import android.support.v7.widget.LinearLayoutManager;

import android.support.v7.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.ArrayList;

import java.util.List;

import java.util.Random;

import tsou.cn.glidetest.adapter.ListAdapter;

import tsou.cn.glidetest.bean.ListBean;

import tsou.cn.glidetest.view.CustomLoadMoreView;

public class ListActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener,

BaseQuickAdapter.RequestLoadMoreListener {

private RecyclerView mRecyclerview;

private SwipeRefreshLayout mSwipeRefresh;

private ListAdapter mAdapter;

private int mLastIndex;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_list);

initView();

initRecyclerView();

initListener();

mAdapter.setEnableLoadMore(false);

mSwipeRefresh.setRefreshing(true);

fetchData(true);

}

private void initView() {

mRecyclerview = (RecyclerView) findViewById(R.id.recyclerview);

mSwipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);

}

private void initRecyclerView() {

mRecyclerview.setLayoutManager(new LinearLayoutManager(this));

mAdapter = new ListAdapter(null);

mAdapter.isFirstOnly(false);

mAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);

mAdapter.setLoadMoreView(new CustomLoadMoreView());

mRecyclerview.setAdapter(mAdapter);

}

private void initListener() {

mSwipeRefresh.setOnRefreshListener(this);

mAdapter.setOnLoadMoreListener(this, mRecyclerview);

}

private boolean mIsRefresh;

private void fetchData(boolean isRefresh) {

mIsRefresh = isRefresh;

if (isRefresh) {

mLastIndex = 1;

}

new AsyncTask<Void, Void, Void>() {

private List lists = new ArrayList<>();

@Override

protected Void doInBackground(Void… voids) {

SystemClock.sleep(3000);

if (mLastIndex <= 3) {

// 加载数据

for (int i = 0; i < 10; i++) {

ListBean listBean = new ListBean();

Random random = new Random();

listBean.setImage(“https://unsplash.it/200/200?random&” + random.nextInt(225));

listBean.setTitle(“刘芳,20岁,河北保定人,9个月前,她辞去了北京一饭店服务员的工作,” +

“来到王庆坨镇一家自行车生产上班,只因为好朋友邀请她,” +

““快来,这里现在有好多共享单车的订单”。” +

““她说他们公司忙都忙不过来,几乎天天在加班。”刘芳说,好友告诉她,” +

“加班很累,但收入可观,多的时候一个月能挣到六七千”);

listBean.setSource(“腾讯网”);

listBean.setStar(random.nextInt(100));

listBean.setEvn(random.nextInt(100));

lists.add(listBean);

}

} else {

lists.clear();

}

return null;

}

@Override

protected void onPostExecute(Void aVoid) {

super.onPostExecute(aVoid);

if (mIsRefresh) {

mAdapter.setNewData(lists);

mSwipeRefresh.setRefreshing(false);

mAdapter.setEnableLoadMore(true);

} else {

if (lists != null) {

if (lists.size() == 0) {

mAdapter.loadMoreEnd();

} else {

mAdapter.addData(lists);

mAdapter.loadMoreComplete();

}

}

}

mLastIndex++;

}

}.execute();

}

@Override

public void onRefresh() {

mAdapter.setEnableLoadMore(false);

fetchData(true);

}

@Override

public void onLoadMoreRequested() {

if (mSwipeRefresh != null) {

mSwipeRefresh.setEnabled(false);

fetchData(false);

mSwipeRefresh.setEnabled(true);

}

}

}

最后使用Glide进行图片加载


package tsou.cn.glidetest.Util;

import android.graphics.drawable.Drawable;

import android.view.View;

import android.widget.ImageView;

import com.bumptech.glide.Glide;

import com.bumptech.glide.load.engine.DiskCacheStrategy;

import com.bumptech.glide.load.resource.drawable.GlideDrawable;

import com.bumptech.glide.request.animation.GlideAnimation;

import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;

import com.bumptech.glide.request.target.Target;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值