這篇文章本來不打算放到進階課程裏面的,就當湊數吧
想實現的目標:既能換掉圖片內容也能用上緩存
所以每次清緩存或者直接不用緩存的方式就不適合我了
首先Glide沒有很明確的對於這問題的api,只能百度。
百度找到個有用的方法:
RequestOptions userAvatarOptions = new RequestOptions()
.signature(new ObjectKey(System.currentTimeMillis()));
Glide.with(ProfileActivity.this).applyDefaultRequestOptions(userAvatarOptions).load(iamgePath).apply(RequestOptions.bitmapTransform(new CircleCrop())).
into(mIvApHeader);
如果你不用緩存,相同圖片鏈接這樣就可以直接更新了
關鍵點:經過測試它會跟.signature(new ObjectKey)走,也就是隻要我的key不一致就用新的,一致就用舊的(也就是用緩存的)
這時就需要接口人員配合了,修改頭像時傳個時間戳給接口,在返回頭像時也再連帶時間戳返回給app
可參考我的處理方案
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public static void displayCircle(Context context, Object path, ImageView imageView) {
if (context != null) {
if (context instanceof Activity && ((Activity) context).isDestroyed()) {
return;
}
RequestOptions userAvatarOptions = null;
if (path instanceof String && path.toString().startsWith("http")){
//是http才處理
if (SharedPreferencesUtils.getLong(context,path.toString(),0) != 0){
//如果之前存儲有該鏈接的key,就直接用上次的
userAvatarOptions = new RequestOptions()
.signature(new ObjectKey(SharedPreferencesUtils.getLong(context,path.toString(),0)))
.circleCrop().autoClone();
} else {
userAvatarOptions = new RequestOptions().circleCrop().autoClone();
}
} else {
userAvatarOptions = new RequestOptions().circleCrop().autoClone();
}
Glide.with(context)
.load(path)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.thumbnail(0.1f)
.placeholder(R.drawable.default_avatar_yuan_40_3x)
.apply(userAvatarOptions)
.into(imageView);
}
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public static void displayCircleAndKey(Context context, Object path,long updateAvatarTimestamp, ImageView imageView) {
if (context != null) {
if (context instanceof Activity && ((Activity) context).isDestroyed()) {
return;
}
RequestOptions userAvatarOptions = null;
if (path instanceof String && path.toString().startsWith("http")){
//是http才處理
if (updateAvatarTimestamp != 0){
//如果傳有緩存key,就直接用它並保存
SharedPreferencesUtils.putLong(context,path.toString(),updateAvatarTimestamp);
userAvatarOptions = new RequestOptions()
.signature(new ObjectKey(updateAvatarTimestamp))
.circleCrop().autoClone();
} else if (SharedPreferencesUtils.getLong(context,path.toString(),0) != 0){
//如果之前存儲有該鏈接的key,就直接用上次的
userAvatarOptions = new RequestOptions()
.signature(new ObjectKey(SharedPreferencesUtils.getLong(context,path.toString(),0)))
.circleCrop().autoClone();
} else {
userAvatarOptions = new RequestOptions().circleCrop().autoClone();
}
} else {
userAvatarOptions = new RequestOptions().circleCrop().autoClone();
}
Glide.with(context)
.load(path)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.thumbnail(0.1f)
.placeholder(R.drawable.default_avatar_yuan_40_3x)
.apply(userAvatarOptions)
.into(imageView);
}
}
關鍵是如何運用好ObjectKey