什么是Glide
An image loading and caching library for Android focused on smooth scrolling
一个使得Android图片列表滑动时更加流畅的图片加载和缓存库。
Glide 优点
(1) Glide 不仅是支持图片缓存和加载,它支持 Gif、WebP、缩略图、Video
(2) 支持优先级处理
(3) 与 Activity/Fragment 生命周期一致,支持 trimMemory
(4) 支持 okhttp、Volley
(5) 与其它图片加载框架相比内存优化更良好
如何使用
Glide.with(this)
.load("http://t.cn/RJqUUdJ")
.placeholder( R.drawable.default )
.error( R.drawable.error)
.into(imageView);
Glide总体设计图
基本概念
RequestManager:请求管理,每一个Activity都会创建一个RequestManager,根据对应Activity的生命周期管理该Activity上所以的图片请求。
Engine:加载图片的引擎,根据Request创建EngineJob和DecodeJob。
EngineJob:图片加载。
DecodeJob:图片处理。
Glide 流程图
Glide 源码解析加载流程
1,Glide.with(初始化构建流程)
核心实现代码
/**
* Begin a load with Glide that will tied to the give {@link android.support.v4.app.FragmentActivity}'s lifecycle
* and that uses the given {@link android.support.v4.app.FragmentActivity}'s default options.
*
* @param activity The activity to use.
* @return A RequestManager for the given FragmentActivity that can be used to start a load.
*/
public static RequestManager with(FragmentActivity activity) {
RequestManagerRetriever retriever = RequestManagerRetriever.get();
return retriever.get(activity);
}
RequestManager supportFragmentGet(Context context, FragmentManager fm) {
SupportRequestManagerFragment current = getSupportRequestManagerFragment(fm);
RequestManager requestManager = current.getRequestManager();
if (requestManager == null) {
requestManager = new RequestManager(context, current.getLifecycle(), current.getRequestManagerTreeNode());
current.setRequestManager(requestManager);
}
return requestManager;
}
RequestManager(Context context, final Lifecycle lifecycle, RequestManagerTreeNode treeNode,
RequestTracker requestTracker, ConnectivityMonitorFactory factory) {
this.context = context.getApplicationContext();
this.lifecycle = lifecycle;
this.treeNode = treeNode;
this.requestTracker = requestTracker;
this.glide = Glide.get(context);
this.optionsApplier = new OptionsApplier();
ConnectivityMonitor connectivityMonitor = factory.build(context,
new RequestManagerConnectivityListener(requestTracker));
// If we're the application level request manager, we may be created on a background thread. In that case we
// cannot risk synchronously pausing or resuming requests, so we hack around the issue by delaying adding
// ourselves as a lifecycle listener by posting to the main thread. This should be entirely safe.
if (Util.isOnBackgroundThread()) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
lifecycle.addListener(RequestManager.this);
}
});
} else {
lifecycle.addListener(this);
}
lifecy