3
我正在爲我的Android應用程序使用滑行庫。如何指定使用Glide for Android加載圖像的重試次數?
我想告訴它在放棄並顯示錯誤佔位符圖像之前,重試獲取圖像X次(可能指數退避!)。
任何想法如何做到這一點? (我正在使用Volley集成btw)。
我正在爲我的Android應用程序使用滑行庫。如何指定使用Glide for Android加載圖像的重試次數?
我想告訴它在放棄並顯示錯誤佔位符圖像之前,重試獲取圖像X次(可能指數退避!)。
任何想法如何做到這一點? (我正在使用Volley集成btw)。
使用您自己的ResourceDecoder。我只加載本地文件,並在decode()
中處理重試計數。如果您使用其他模型,只需轉到相應的界面。
Glide 4.0.0-SNAPSHOT的示例。 定製ResourceDecoder:
public class FileDecoder implements ResourceDecoder<File, Drawable>{
private final Context context;
private int retryCounter = 0;
public FileDecoder(Context context) {
this.context = context;
}
@Override
public Resource<Drawable> decode(File source, int width, int height, Options options) throws IOException{
source = getTheFile(); //loading the image from a zip
final Drawable icon = Drawable.createFromPath(source.getAbsolutePath());
if(icon == null){
if(retryCounter < 3){
retryCounter++;
return decode(source, width, height, options);
}
return null;
}
return new DrawableResource<Drawable>(icon) {
@Override public Class<Drawable> getResourceClass() {
return Drawable.class;
}
@Override public int getSize() {
if (drawable instanceof BitmapDrawable) {
return Util.getBitmapByteSize(((BitmapDrawable) drawable).getBitmap());
} else {
return 1;
}
}
@Override public void recycle() {}
};
}
@Override public boolean handles(File source, Options options) throws IOException {
return true;
}
}
所需的自定義ModelLoader
public class FileModelLoader implements ModelLoader<File, File>{
@Nullable @Override
public LoadData<File> buildLoadData(final File file, int width, int height, Options options){
return new LoadData<>(new ObjectKey(file), new DataFetcher<File>() {
@Override
public void loadData(Priority priority, DataCallback<? super File> callback) {
callback.onDataReady(file);
}
@Override public void cleanup() {
}
@Override public void cancel() {
}
@Override public Class<File> getDataClass() {
return File.class;
}
@Override public DataSource getDataSource() {
return DataSource.LOCAL;
}
});
}
@Override public boolean handles(File file){
return true;
}
}
註冊自定義模塊
public class CustomGlideModule implements GlideModule{
@Override public void applyOptions(Context context, GlideBuilder builder){
builder.setDefaultRequestOptions(RequestOptions.formatOf(DecodeFormat.PREFER_RGB_565)); //less memory consumption but less quality
}
@Override public void registerComponents(Context context, Registry registry){
registry.append(File.class, File.class, new ModelLoaderFactory<File, File>(){
@Override public ModelLoader<File, File> build(MultiModelLoaderFactory multiFactory){
return new FileModelLoader();
}
@Override public void teardown(){
}
}).append(File.class, Drawable.class, new FileDecoder(context));
}
}
添加到mainfest
<application>
...
<meta-data
android:name="com.fileloader.glide.CustomGlideModule"
android:value="GlideModule" />
</application>