Glide入门教程(13)整合网络协议栈

整合网络协议栈

       通过HTTP/HTTPS从网络下载图片,是显示图片的一个重要的环节。虽然标准的Android网络包可以完成这些工作,但是仍然有很多开发者为了改善android的网络做了一些开发。每个库都有自己的优点和缺点。最终取决于项目的实际需求和开发者的个人爱好。

       Glide的开发者不强迫你使用他们推荐的网络库。所以,Glide是无关HTTP/S的。理论上,它能实现基本的网络功能,在任何情况下工作。它需要一个Glide的ModelLoader的接口设置。为了让这个更简单,Glide提供了两个网络库的支持:OkHttp 和 Volley。

OkHttp 2

       如果想要用OkHttp 2作为你的Glide网络库,可以手动通过定义一个GlideModule来实现整合。如果你想要避免手动整合,那就打开build.gradle,然后添加下面的依赖:

1
2
3
4
5
6
7
8
9
10
11
dependencies {  
// your other dependencies
// ...

// Glide
compile 'com.github.bumptech.glide:glide:3.7.0'

// Glide's OkHttp2 Integration
compile 'com.github.bumptech.glide:okhttp-integration:1.4.0@aar'
compile 'com.squareup.okhttp:okhttp:2.7.5'
}

       Gradle会自动合入必须的GlideModule到你的Android.Manifest中。Glide会识别manifest里的东西,并为所有的网络连接使用OkHttp。

Volley

       如果你偏向于使用Volley,你必须把build.gradle依赖改成下面的:

1
2
3
4
5
6
7
8
9
10
11
dependencies {  
// your other dependencies
// ...

// Glide
compile 'com.github.bumptech.glide:glide:3.7.0'

// Glide's Volley Integration
compile 'com.github.bumptech.glide:volley-integration:1.4.0@aar'
compile 'com.mcxiaoke.volley:library:1.0.8'
}

       这会添加Volley和集成库(integration library)到你的项目中。集成库添加GlideModule到你的Android.Manifest文件中。Glide会自动识别,然后使用Volley作为网络连接库。

       注意:如果你同时定义了2个库在你的build.gradle,两个都会被添加。由于Glide不能按照任何特别的顺序加载它们,不知道哪个库实际上被调用,可能会导致不稳定的结果。请确保你只添加了一个集成库。

OkHttp 3

       如果你想要使用最新的OkHttp 3作为网络协议栈,使用如下配置:

1
2
3
4
5
6
7
8
9
10
11
ependencies {  
// your other dependencies
// ...

// Glide
compile 'com.github.bumptech.glide:glide:3.7.0'

// Glide's OkHttp3 Integration
compile 'com.github.bumptech.glide:okhttp3-integration:1.4.0@aar'
compile 'com.squareup.okhttp3:okhttp:3.2.0'
}

其他网络库

       Glide并不支持除了Volley、OkHttp2和OkHttp3以外的库。然而,你可以通过在Github上推送一个请求,尽情集成你喜欢的库到Glide里。Volley、OkHttp2和OkHttp3的集成可以给你一个指导方向。

参考资料:
签到钱就到 Glide入门教程——15.整合网络协议栈

Fork me on GitHub