Glide遇到的问题与解决方法
在使用中遇到的问题记载。
适配androidx问题
遇到android.support.annotation.NonNull找不到问题
由于目前新项目已经都迁移到了androidx原因,已经移除了support包了。这里需要作出以下修改:
- 修改
gradle.properties
文件,添加如下:
android.useAndroidX=true
# Automatically convert third-party libraries to use AndroidX
android.enableJetifier=true
- 保持最新版本一致,主要如下:
api 'com.github.bumptech.glide:annotations:4.9.0'
api 'com.github.bumptech.glide:glide:4.9.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'
- 添加androidx注解处理器:
annotationProcessor 'androidx.annotation:annotation:1.1.0'
完成上面三步后(可先删除build目录下的错误文件),重新编译build,就正常了:
播放gif速率慢问题
记:有一次线上问题,说一华为手机加载gif后,播放速率跟预期的慢很多。百度得到一些得到解决方案:一、使用android-gif-drawable
库去加载gif;二、反射glide代码去修改速率。这里给出第二种解决方案代码:
GlideApp.with(mContext)
.asGif()
.load(R.drawable.icon_wumaheyi_guide)
.apply(requestOptions)
.into(new SimpleTarget<GifDrawable>(){
/**
* The method that will be called when the resource load has finished.
*
* @param resource the loaded resource.
* @param transition
*/
@Override
public void onResourceReady(GifDrawable resource, Transition<? super GifDrawable> transition) {
try {
Field field = GifDecoder.class.getDeclaredField("header");
field.setAccessible(true);
GifHeader header = (GifHeader) field.get(resource.getFirstFrame());
Field field2 = GifHeader.class.getDeclaredField("frames");
field2.setAccessible(true);
List frames = (List) field2.get(header);
if (frames.size()>0){
Field delay = frames.get(0).getClass().getDeclaredField("delay");
delay.setAccessible(true);
for (Object frame : frames) {
delay.set(frame,40);//这里直接给修改成了20
}
}
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
mIvGoTask.setImageDrawable(resource);
resource.setLoopCount(Integer.MAX_VALUE);
resource.start();
}
});
使用了反射,要注意keep避免混淆
glide activity has been destroyed
上下文销毁了,glide加载的生命周期是创建一个fragment依靠于activity,所以当activity销毁时候就会报以上错。解决方式:判断空、使用Application上下文。
if(mContext instanceof Activity){
if (((Activity) mContext).isDestroyed() || ((Activity) mContext).isFinishing()) {
return;
}
}