本篇主要由以下内容构成:
1、框架结构简介
2、按照glide源码使用的时序图进行深入简述的方式讲解
3、核心类和核心模块总结
ps:本人博客写的太少,逻辑有时会走火入魔,希望你看到我的文章,可以理清自己的思路,哈哈,开玩笑。闲话少说,我们来开车,希望老司机来飙车,本篇主要记录自己学习的内容,如果能帮助其他的司机更是好极了。

废话太多,我们开车。

  1. 框架结构

好了:我这里项目用的是glie-3.7.0的源码,虽然每个源码,有点出入,但是结构上还是没有什么区别的。
它分为:加载策略: load包>data>
主要有:HttpUrlFetcher 网络加载
LocalUriFetcher 本地加载
MediaStoreThumbFetcher 媒体加载 童鞋们可以自己对着看一下

缓存策略: engine>cache
里面有:MemoryCache DiskCache 这里先不说这些
转发策略占和上面的放到下一篇再说。

2.好了我们来根据常用的代码来进一步分析:

Glide.with(mApplication).load(url).into(target);

我们主要来分析一下常用的功能: 先从with下手,`public static RequestManager with(Context context) {RequestManagerRetriever retriever = RequestManagerRetriever.get();
        return retriever.get(context);}/*** Begin a load with Glide that will be tied to the given {@link android.app.Activity}'s lifecycle and that uses the* given {@link Activity}'s default options.** @param activity The activity to use.* @return A RequestManager for the given activity that can be used to start a load.*/public static RequestManager with(Activity activity) {RequestManagerRetriever retriever = RequestManagerRetriever.get();
        return retriever.get(activity);}/*** 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);}
/*** Begin a load with Glide that will be tied to the given {@link android.app.Fragment}'s lifecycle and that uses* the given {@link android.app.Fragment}'s default options.** @param fragment The fragment to use.* @return A RequestManager for the given Fragment that can be used to start a load.*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static RequestManager with(android.app.Fragment fragment) {RequestManagerRetriever retriever = RequestManagerRetriever.get();return retriever.get(fragment);

我们看到有很多重载方法,glide已经给你考虑非常周全了,我们只看这个重载方法

public static RequestManager with(FragmentActivity activity) { RequestManagerRetriever retriever = RequestManagerRetriever.get(); return retriever.get(activity);}
ok 我们点入 retriever.get(activity),进入  RequestManagerRetriever 这个类,

好了我们接着往下走:

//调用这个方法public RequestManager get(Context context) {if (context == null) {throw new IllegalArgumentException("You cannot start a load on a null Context");//判断是否在主线程} else if (Util.isOnMainThread() && !(context instanceof Application)) {if (context instanceof FragmentActivity) {return get((FragmentActivity) context);} else if (context instanceof Activity) {return get((Activity) context);} else if (context instanceof ContextWrapper) {return get(((ContextWrapper) context).getBaseContext());}}return getApplicationManager(context);}

我们接着看,supportFragmentGet(fragment.getActivity(), fm);做了什么诡秘的操作:

RequestManager supportFragmentGet(Context context, FragmentManager fm) {//OK 瞪着我们大眼和记住这个类  SupportRequestManagerFragment 这个就是一个空的FragmentSupportRequestManagerFragment current = getSupportRequestManagerFragment(fm);RequestManager requestManager = current.getRequestManager();if (requestManager == null) {requestManager = new RequestManager(context, current.getLifecycle(), current.getRequestManagerTreeNode());current.setRequestManager(requestManager);}return requestManager;}

我们看到上面的代码,取出一个 SupportRequestManagerFragment 我们进入代码看看它是什么,还都有什么:

//这个一个fragment
public class SupportRequestManagerFragment extends Fragment {//还要记住这个成员变量 它是观察者private RequestManager requestManager;//记住这个成员变量 ActivityFragmentLifecycle lifecycle  它是一个被观察者,它接管了fragemnt//的生命周期private final ActivityFragmentLifecycle lifecycle;private final RequestManagerTreeNode requestManagerTreeNode =new SupportFragmentRequestManagerTreeNode();private final HashSet<SupportRequestManagerFragment> childRequestManagerFragments =new HashSet<SupportRequestManagerFragment>();private SupportRequestManagerFragment rootRequestManagerFragment;public SupportRequestManagerFragment() {this(new ActivityFragmentLifecycle());}// For testing only.@SuppressLint("ValidFragment")public SupportRequestManagerFragment(ActivityFragmentLifecycle lifecycle) {this.lifecycle = lifecycle;}/*** Sets the current {@link com.bumptech.glide.RequestManager}.** @param requestManager The manager to set.*/public void setRequestManager(RequestManager requestManager) {this.requestManager = requestManager;}ActivityFragmentLifecycle getLifecycle() {return lifecycle;}/*** Returns the current {@link com.bumptech.glide.RequestManager} or null if none is set.*/public RequestManager getRequestManager() {return requestManager;}/*** Returns the {@link RequestManagerTreeNode} that provides tree traversal methods relative to the associated* {@link RequestManager}.*/public RequestManagerTreeNode getRequestManagerTreeNode() {return requestManagerTreeNode;}private void addChildRequestManagerFragment(SupportRequestManagerFragment child) {childRequestManagerFragments.add(child);}private void removeChildRequestManagerFragment(SupportRequestManagerFragment child) {childRequestManagerFragments.remove(child);}
}

好的,先只要记住我注释的几个类,待会一一揭开他们的面目,我们来看看getSupportRequestManagerFragment(final FragmentManager fm)这个方法都做了什么?

SupportRequestManagerFragment getSupportRequestManagerFragment(final FragmentManager fm) {SupportRequestManagerFragment current = (SupportRequestManagerFragment) fm.findFragmentByTag(FRAGMENT_TAG);if (current == null) {current = pendingSupportRequestManagerFragments.get(fm);if (current == null) {current = new SupportRequestManagerFragment();pendingSupportRequestManagerFragments.put(fm, current);//看到这里是不是知道,我们上面创造的SupportRequestManagerFragment如何当前页面绑定的就是在这里开始绑定的,通过添加事务的方法。fm.beginTransaction().add(current, FRAGMENT_TAG).commitAllowingStateLoss();handler.obtainMessage(ID_REMOVE_SUPPORT_FRAGMENT_MANAGER, fm).sendToTarget();}}return current;}

我们再会到supportFragmentGet(Context context, FragmentManager fm)这个方法;

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;}

我们来在说说 SupportRequestManagerFragment 里面的生命周期方法是如何被 ActivityFragmentLifecycle lifecycle;接管的

@Overridepublic void onStart() {super.onStart();
//看见没有   ActivityFragmentLifecycle    lifecyclelifecycle.onStart();}@Overridepublic void onStop() {super.onStop();lifecycle.onStop();}@Overridepublic void onDestroy() {super.onDestroy();lifecycle.onDestroy();}

那你肯定要问了 ActivityFragmentLifecycle lifecycle到底是个什么玩意呢?
我们来看看:

 //实现了 Lifecycle 接口, 然后又有 addListener(LifecycleListener listener)方法,一看就像观察者套路
class ActivityFragmentLifecycle implements Lifecycle {private final Set<LifecycleListener> lifecycleListeners =Collections.newSetFromMap(new WeakHashMap<LifecycleListener, Boolean>());private boolean isStarted;private boolean isDestroyed;/*** Adds the given listener to the list of listeners to be notified on each lifecycle event.** <p>*     The latest lifecycle event will be called on the given listener synchronously in this method. If the*     activity or fragment is stopped, {@link LifecycleListener#onStop()}} will be called, and same for onStart and*     onDestroy.* </p>** <p>*     Note - {@link com.bumptech.glide.manager.LifecycleListener}s that are added more than once will have their*     lifecycle methods called more than once. It is the caller's responsibility to avoid adding listeners*     multiple times.* </p>*/@Overridepublic void addListener(LifecycleListener listener) {lifecycleListeners.add(listener);if (isDestroyed) {listener.onDestroy();} else if (isStarted) {listener.onStart();} else {listener.onStop();}}void onStart() {isStarted = true;for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {lifecycleListener.onStart();}}void onStop() {isStarted = false;for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {lifecycleListener.onStop();}}void onDestroy() {isDestroyed = true;for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {lifecycleListener.onDestroy();}}
}

好我们来看看Lifecycle 这个接口有啥宝贝:我们要记住这个LifecycleListener 这个接口

*** An interface for listening to Activity/Fragment lifecycle events.*/
public interface Lifecycle {/*** Adds the given listener to the set of listeners managed by this Lifecycle implementation.*/void addListener(LifecycleListener listener);
}

好了,我们还是去看看LifecycleListener 这个接口有啥好东西,好像里面就是一些感觉定义的是生命周期的方法,但是它是如何和ActivityFragmentLifecycle lifecycle 完成这个订阅的观察者模式呢?

/*** An interface for listener to {@link android.app.Fragment} and {@link android.app.Activity} lifecycle events.*/
public interface LifecycleListener {/*** Callback for when {@link android.app.Fragment#onStart()}} or {@link android.app.Activity#onStart()} is called.*/void onStart();/*** Callback for when {@link android.app.Fragment#onStop()}} or {@link android.app.Activity#onStop()}} is called.*/void onStop();/*** Callback for when {@link android.app.Fragment#onDestroy()}} or {@link android.app.Activity#onDestroy()} is* called.*/void onDestroy();
}

好,还记得这个方法么?

 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;}//我们把2个方法放在一起看一下  SupportRequestManagerFragment getSupportRequestManagerFragment(final FragmentManager fm) {SupportRequestManagerFragment current = (SupportRequestManagerFragment) fm.findFragmentByTag(FRAGMENT_TAG);if (current == null) {current = pendingSupportRequestManagerFragments.get(fm);if (current == null) {current = new SupportRequestManagerFragment();pendingSupportRequestManagerFragments.put(fm, current);fm.beginTransaction().add(current, FRAGMENT_TAG).commitAllowingStateLoss();handler.obtainMessage(ID_REMOVE_SUPPORT_FRAGMENT_MANAGER, fm).sendToTarget();}}return current;}
//它会new SupportRequestManagerFragment(); //最后在SupportRequestManagerFragment内 中实例一个public SupportRequestManagerFragment() {this(new ActivityFragmentLifecycle());}

到了本篇最重要的一个类了RequestManager,我们在上面代码可以看见 ,将ActivityFragmentLifecycle作为参数,传入到RequestManager 构造方法里了。

  if (requestManager == null) {requestManager = new RequestManager(context, current.getLifecycle(), current.getRequestManagerTreeNode());current.setRequestManager(requestManager);}

那既然这样,我们就去RequestManager里面看看,我们先看看这个类都有啥,代码太多我们只看关键的

//惊喜的发现,RequestManager 居然实现LifecycleListener 接口,如果不记得了请自己在看下源码
public class RequestManager implements LifecycleListener {private final Context context;private final Lifecycle lifecycle; private final RequestManagerTreeNode treeNode;private final RequestTracker requestTracker;private final Glide glide;private final OptionsApplier optionsApplier;private DefaultOptions options;public RequestManager(Context context, Lifecycle lifecycle, RequestManagerTreeNode treeNode) {this(context, lifecycle, treeNode, new RequestTracker(), new ConnectivityMonitorFactory());}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 (Util.isOnBackgroundThread()) {new Handler(Looper.getMainLooper()).post(new Runnable() {@Overridepublic void run() {lifecycle.addListener(RequestManager.this);}});} else {lifecycle.addListener(this);  //看到这里没有,将RequestManager作为观察者,添加到集合里了}lifecycle.addListener(connectivityMonitor);}
}
   lifecycle.addListener(this);  看到这里没有,将RequestManager作为观察者,添加到集合里了。

我们来看看RequestManager如何处理生命周期的?如何解决glide生命周期和activity、fragment等进行同步的,

 @Overridepublic void onStart() {// onStart might not be called because this object may be created after the fragment/activity's onStart method.resumeRequests();}/*** Lifecycle callback that unregisters for connectivity events (if the android.permission.ACCESS_NETWORK_STATE* permission is present) and pauses in progress loads.*/@Overridepublic void onStop() {pauseRequests();}/*** Lifecycle callback that cancels all in progress requests and clears and recycles resources for all completed* requests.*/@Overridepublic void onDestroy() {requestTracker.clearRequests();

我们这里在在看看 resumeRequests();方法,其他的实现,请同学自己看下源码,

 public void resumeRequests() {Util.assertMainThread();requestTracker.resumeRequests();}

接着往下看

  /**开始执行请求* Starts any not yet completed or failed requests.*/public void resumeRequests() {isPaused = false;for (Request request : Util.getSnapshot(requests)) {if (!request.isComplete() && !request.isCancelled() && !request.isRunning()) {request.begin();}}pendingRequests.clear();}

好了,到目前为止我们将with的方法说完了,不知道你看懂没有,没有看懂的话,我建议按照这个源码自己多走几遍就好了。

我们来总结下一些关键的类:
RequestManagerRetriever SupportRequestManagerFragment RequestManager

关键的接口: Lifecycle ActivityFragmentLifecycle LifecycleListener

我们在走一遍流程:
Glide.with–> RequestManagerRetriever retriever.get(context)—>retriever.supportFragmentGet(activity, fm)—>retriever.getSupportRequestManagerFragment(FragmentManager fm)

推荐一个比较好的建模工具powerdesigner

附上glide的调用时序图:

Glide源码解析之山清水秀疑无路(一)相关推荐

  1. Glide 源码解析之监听生命周期

    code小生 一个专注大前端领域的技术平台公众号回复Android加入安卓技术群 作者:断了谁的弦 链接:https://www.jianshu.com/p/1169a91342a9 声明:本文已获断 ...

  2. Glide源码解析-加载流程

    1 引言 一直想要阅读Glide源码,但是苦于时间和功力都不够,总是断断续续的,趁着现在有一些空暇时间,来简要分析Glide的源码.Glide的实现太过复杂,不可能做到面面俱到,如果每一行都细致分析, ...

  3. android glide流程解析,Glide 源码解析(一):简单流程分析

    这篇文章上次修改于 839 天前,可能其部分内容已经发生变化,如有疑问可询问作者. 这篇文章是这个系列的第一篇文章,我第一次写这样连续系列的文章,我先一层一层的剥开 Glide ,如果谁有更好的想法欢 ...

  4. Glide源码解析2 -- 生命周期原理

    一 概述 Glide 中一个重要的特性就是Request可以绑定Activity或者fragment的onStart而resume,onStop而pause,onDestroy而clear,所以Gli ...

  5. BAT高级架构师合力熬夜15天,肝出了这份PDF版《Android百大框架源码解析》,还不快快码住。。。

    前言 为什么要阅读源码? 现在中高级Android岗位面试中,对于各种框架的源码都会刨根问底,从而来判断应试者的业务能力边际所在.但是很多开发者习惯直接搬运,对各种框架的源码都没有过深入研究,在面试时 ...

  6. glide源码中包含了那种设计模式_月薪20+的程序员面试都问这些高端技术题(含答案+面试指导)...

    不知道大家有没有发现,最近情况在慢慢好转,现在我们小区已经解控了,再也不要绕远路出门了,可喜可贺. 当然,我们的金三银四马上也要发挥它该有的作用了,尚未找到工作的朋友们,准备好了吗? 今天给大家带来的 ...

  7. glide源码中包含了那种设计模式_腾讯阿里华为小米等大厂Android高端面试题145题(含部分详解)-Go语言中文社区...

    前言 本篇是结合我之前面试别人的经验,以及跟一些在大厂待过的朋友,讨论总结出的一份很全面的大公司需要用到的一些高端Android技术.这里也专门整理了一个文档,重点和难点都有详细解析. 这些题目有点技 ...

  8. Set接口的源码解析+扩容机制

    Set集合 Set的接口介绍 无序(添加和需要的顺序是不一样的)没有索引 不允许重复元素,所以最多包含一个null 添加和取出的顺序是不固定的. 虽然不是添加的顺序,但是顺序是固定的 Set的常用方法 ...

  9. Glide 4.9源码解析-缓存策略

    本文Glide源码基于4.9,版本下载地址如下:Glide 4.9 前言 在分析了Glide的图片加载流程后,更加发觉到Glide的强大,于是这篇文章将继续深入分析Glide的缓存策略.不过今天的文章 ...

最新文章

  1. oracle加undo+resize,How To resize undo tablespace in Oracle
  2. 关注点分离之RestTemplate的错误处理
  3. 详细分析 apache httpd 反向代理的用法
  4. 摇杆怎么映射到键盘_[评测]YAMAHA PSRSX900:雅马哈升级幅度最大的高端编曲键盘键盘中国原创评测...
  5. C++中类和对象的一些注意事项
  6. 2017.3.6 地精部落 思考记录
  7. 随想录(cmake编译)
  8. C语言通过modf()函数实现小数分离
  9. # Idea,2.5,软件安装,提示If you already have a 64-bit JDK installed ,defined a JAVA_HOME variable in Compu
  10. 多重阴影的设置、鼠标激活时、相邻选择器的简介、display
  11. 内网漫游(lateral movement)的破解之道
  12. SpringBoot的banner竟然可以用美女图片在线制作,难以相信
  13. 解决安装pycrypto时的各种问题/安装失败
  14. 【AI测试】人工智能测试整体介绍——第六部分
  15. 浪潮优派培训笔记:Tomcat服务器
  16. 如何截取视频中的中间部分视频,批量去除片头片尾
  17. 短视频内容创业,注定只是少数人的游戏
  18. 文本表示(Text Representation)之词集模型(SOW)词袋模型(BOW)TF-IDF模型
  19. [极客大挑战 2019]LoveSQL
  20. Android的模拟器能不能照相,android模拟器无法使用camera拍照

热门文章

  1. 系统静态分析建模(类图)
  2. jsp药品信息管理系统 myeclipse开发mysql数据库
  3. 树叶贴画机器人_学生手工论文,关于对学前教育手工课教学相关参考文献资料-免费论文范文...
  4. 小学四年级计算机制作月历教案,小学信息技术教案制作月历
  5. 超细的CSS学习笔记(CSS详解)
  6. 几何图形识别 python_OpenCV中几何形状识别与测量
  7. html在边框线中加文本框,怎么设置幻灯片里的文本框边框线?
  8. 如何用DreamMail (DM Pro) 模板提高工作效率?
  9. Java之旅(十一)
  10. 数组名与数组名取地址的差异