在ipv6环境下可能会出现网络无法加载的情况,我们可以考虑使用ipv4优先的方案设置dns以加快网络加载速度。
1. 设置okhttp优先使用ipv4
/**
* wifi环境下优先使用ipv4
*/
public class MyDns implements Dns {
@Override
public List<InetAddress> lookup(String hostname) throws UnknownHostException{
if (hostname == null){
throw new UnknownHostException ("hostname == null") ;
}else{
try{
List<InetAddress> inetAddressList = new ArrayList<>();
InetAddress[] inetAddresses = InetAddress.getAllByName (hostname) ;
for (InetAddress inetAddress: inetAddresses){
if (inetAddress instanceof Inet4Address){
inetAddressList.add(0, inetAddress) ;
}else{
inetAddressList.add(inetAddress);
}
}
return inetAddressList;
}catch (NullPointerException var4){
UnknownHostException unknownHostException = new UnknownHostException("Broken system behavior");
unknownHostException.initCause(var4);
throw unknownHostException;
}
}
}
}
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.dns(new MyDns());
OkHttpClient client = builder.build();
2. 设置图片框架Glide优先ipv4
- 引入
implementation 'com.github.bumptech.glide:glide:4.11.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
implementation "com.github.bumptech.glide:okhttp3-integration:4.11.0"
- 自定义类继承AppGlideModule,添加类注解@GlideModule
@GlideModule
public class OkHttpGlideModule extends AppGlideModule {
@Override
public boolean isManifestParsingEnabled() {
return false;
}
@Override
public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {
super.registerComponents(context, glide, registry);
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.dns(new MyDns());
builder.followRedirects(true);
// 设置连接超时
builder.connectTimeout(10, TimeUnit.SECONDS);
// 设置socket超时
builder.readTimeout(60, TimeUnit.SECONDS);
builder.writeTimeout(60, TimeUnit.SECONDS);
OkHttpClient okHttpClient = builder.build();
registry.replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(okHttpClient));
}
}
- 在AndroidManifest.xml中<application>中添加<meta-data>项,如:
<meta-data
android:name="com.xxx.xxx.OkHttpGlideModule"
android:value="AppGlideModule"/>
- 混淆
-keep public class * implements com.bumptech.glide.module.GlideModule
-keep public class * extends com.bumptech.glide.module.AppGlideModule
-keep public enum com.bumptech.glide.load.ImageHeaderParser$**{
**[] $VALUES;
public *;
}
-keep class com.bumptech.glide.GeneratedAppGlideModuleImpl {*;}
网友评论