Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

android - How to set OkHttpClient for glide

I am using Glide to load images, the issue I'm facing is that when i run app on slow internet connection I'm getting SocketTimeOutException. So to solve this issue i want to use a custom OkHttpClient so that I can change the timeout of HttpClient this is the code i have.

public class MyGlideModule  implements GlideModule {
    @Override
    public void applyOptions(Context context, GlideBuilder builder) {

    }

    @Override
    public void registerComponents(Context context, Glide glide) {
        OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(15, TimeUnit.SECONDS);
        client.setReadTimeout(15,TimeUnit.SECONDS);
        OkHttpUrlLoader.Factory factory = new OkHttpUrlLoader.Factory(client);
        glide.register(GlideUrl.class, InputStream.class, factory);
    }
}

but OkHttpUrlLoader is not there any more in Glide API. So i was wondering how can set the OkHttpClient for Glide

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

since glide 4.0.0 it has changed a little bit.

first of all GlideModule is deprecated and you need to use AppGlideModule if you are developing an application and LibraryGlideModule for library development. you need to use @GlideModule above your custom AppGlideModule class.

secondly there is no register() method in Glide object any more.

and finally okhttp3 will use a builder.

it'll be like below for apps:

    @GlideModule
    private class CustomGlideModule extends AppGlideModule {

       @Override
       public void registerComponents(Context context, Glide glide, Registry registry) {
           OkHttpClient client = new OkHttpClient.Builder()
                   .readTimeout(15, TimeUnit.SECONDS)
                   .connectTimeout(15, TimeUnit.SECONDS)
                   .build();

       OkHttpUrlLoader.Factory factory = new OkHttpUrlLoader.Factory(client);

           glide.getRegistry().replace(GlideUrl.class, InputStream.class, factory);
       }
   }

you'll need to have all these dependency with the exact versions in your app gradle file:

 compile "com.squareup.okhttp3:okhttp:3.8.1"
    compile 'com.github.bumptech.glide:glide:4.0.0'
    compile ('com.github.bumptech.glide:okhttp3-integration:4.0.0'){
        exclude group: 'glide-parent'
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...