android替换Glide通讯组件为Okhttp并监控加载进度,安卓rxjava获取网络时间
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.ModelLoader;
import com.bumptech.glide.load.model.ModelLoaderFactory;
import java.io.InputStream;
import okhttp3.OkHttpClient;
/**
- 仿照HttpUrlGlideUrlLoader
*/
public class OkHttpGlideUrlLoader implements ModelLoader<GlideUrl, InputStream> {
private OkHttpClient okHttpClient;
public static class Factory implements ModelLoaderFactory<GlideUrl, InputStream> {
private OkHttpClient client;
public Factory() {
}
public Factory(OkHttpClient client) {
this.client = client;
}
private synchronized OkHttpClient getOkHttpClient() {
if (client == null) {
client = new OkHttpClient();
}
return client;
}
@Override
public ModelLoader<GlideUrl, InputStream> build(Context context, GenericLoaderFactory factories) {
return new OkHttpGlideUrlLoader(getOkHttpClient());
}
@Override
public void teardown() {
}
}
public OkHttpGlideUrlLoader(OkHttpClient client) {
this.okHttpClient = client;
}
@Override
public DataFetcher getResourceFetcher(GlideUrl model, int width, int height) {
return new OkHttpFetcher(okHttpClient, model);
}
}
自定義MyGlideModule注冊OkHttpGlideUrlLoader
package tsou.cn.glidetest.Glide;
import android.content.Context;
import com.bumptech.glide.Glide;
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;
最后
**一個零基礎的新人,我認為堅持是最最重要的。**我的很多朋友都找我來學習過,我也很用心的教他們,可是不到一個月就堅持不下來了。我認為他們堅持不下來有兩點主要原因:
他們打算入行不是因為興趣,而是因為所謂的IT行業工資高,或者說完全對未來沒有任何規劃。
剛開始學的時候確實很枯燥,這確實對你是個考驗,所以說堅持下來也很不容易,但是如果你有興趣就不會認為這是累,不會認為這很枯燥,總之還是貴在堅持。
技術提升遇到瓶頸了?缺高級Android進階視頻學習提升自己嗎?還有大量大廠面試題為你面試做準備!
點擊:Android 學習,面試文檔,視頻收集大整理
來獲取學習資料提升自己去挑戰一下BAT面試難關吧
對于很多Android工程師而言,想要提升技能,往往是自己摸索成長,不成體系的學習效果低效漫長且無助。整理的這些知識圖譜希望對Android開發的朋友們有所參考以及少走彎路,本文的重點是你有沒有收獲與成長,其余的都不重要,希望讀者們能謹記這一點。
不論遇到什么困難,都不應該成為我們放棄的理由!
如果有什么疑問的可以直接私我,我盡自己最大力量幫助你!
/tv_list_home_focus"
android:singleLine=“true”
android:text="@string/source"
android:textColor="@android:color/darker_gray"
android:textSize=“12sp” />
主頁面代碼邏輯
package tsou.cn.glidetest;
最后
**一個零基礎的新人,我認為堅持是最最重要的。**我的很多朋友都找我來學習過,我也很用心的教他們,可是不到一個月就堅持不下來了。我認為他們堅持不下來有兩點主要原因:
他們打算入行不是因為興趣,而是因為所謂的IT行業工資高,或者說完全對未來沒有任何規劃。
剛開始學的時候確實很枯燥,這確實對你是個考驗,所以說堅持下來也很不容易,但是如果你有興趣就不會認為這是累,不會認為這很枯燥,總之還是貴在堅持。
技術提升遇到瓶頸了?缺高級Android進階視頻學習提升自己嗎?還有大量大廠面試題為你面試做準備!
點擊:Android 學習,面試文檔,視頻收集大整理
來獲取學習資料提升自己去挑戰一下BAT面試難關吧
[外鏈圖片轉存中…(img-8HTri7YH-1646139637602)]
對于很多Android工程師而言,想要提升技能,往往是自己摸索成長,不成體系的學習效果低效漫長且無助。整理的這些知識圖譜希望對Android開發的朋友們有所參考以及少走彎路,本文的重點是你有沒有收獲與成長,其余的都不重要,希望讀者們能謹記這一點。
不論遇到什么困難,都不應該成為我們放棄的理由!
如果有什么疑問的可以直接私我,我盡自己最大力量幫助你!
最后祝各位新人都能堅持下來,學有所成。
總結
以上是生活随笔為你收集整理的android替换Glide通讯组件为Okhttp并监控加载进度,安卓rxjava获取网络时间的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: AUTOCAD——沿着线种树
- 下一篇: 如何创新并发出发明专利——以毕设设计电路