其他分享
首页 > 其他分享> > 如何使用Okhttp3和GlideV4设置超时?

如何使用Okhttp3和GlideV4设置超时?

作者:互联网

我正在使用glide v4和okhttp3与glide集成.我想更改它的超时时间.怎么做?通过扩展AppGlideModule还是还有其他方法?我已经搜索了正确的文档,但没有找到任何地方.

解决方法:

您可以通过创建一个类来更改超时,该类扩展了AppGlideModule并具有@GlideModule批注.然后,您覆盖方法registerComponents并在其中内部,可以创建一个新的OkHttpClient,可用于控制Glide请求超时.

首先,您应该在build.gradle文件中添加Glide和OkHttp3 Glide Integration库gradle依赖项:

compile 'com.github.bumptech.glide:glide:4.2.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.2.0'
compile("com.github.bumptech.glide:okhttp3-integration:4.2.0") {
    exclude group: 'glide-parent'
}

第二,自定义GlideAppModule类的示例代码:

@GlideModule
public class MyGlideAppModule extends AppGlideModule {
    @Override
    public void registerComponents(Context context, Glide glide, Registry registry) {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();

        OkHttpUrlLoader.Factory factory = new OkHttpUrlLoader.Factory(client);
        glide.getRegistry().replace(GlideUrl.class, InputStream.class, factory);
    }
}

感谢提供解决方案的Amir Ziarati

另外,有关Glide 3.x和Glide 4.x之间差异的更多信息,请参考关于模块的Glide自定义的this article.

标签:okhttp3,android-glide,android
来源: https://codeday.me/bug/20191025/1931085.html