为什么要写这篇新手向源码分析
很多人拿到源码的时候不知从哪下手,而且源码量级由于太大,往往看到某个地方就会被细枝末节的地方打扰,从而看了半天不知所以然,源码的阅读是很讲究效率,能否得到最想要知道的信息,能否最短的时间搞通流程,之后再研究细节,这个很重要。也就是大佬们说的不要因为一棵树放弃整个森林。闲话不多说,我们开始。
准备工作
三方代码最好的查看代码方式不是下载源码,往往github上有三方代码,如果有三方类库引用的话,最好直接项目中引用,这样在项目引用jar包中打开,节省了源码编译等一系列问题。之后了解到最简单的引用方式即可。
Glide的话我们只需要在项目中集成
implementation 'com.github.bumptech.glide:glide:4.11.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
Glide4.11版本github上用法是新建一个GlideMoudle
@GlideModule
public class ContactUriModule extends AppGlideModule {
// Intentionally empty.
}
之后最简单的使用方法就是
GlideApp.with(context).load("").into(imageView)
到此为止,源码分析准备工作完成了。
源码分析
虽然看起来使用很简单,一行代码就完成了,但Glide背后包括了缓存,请求.. 一系列操作。
首先GlideApp.with(context),进去会发现就是和以前的Glide.with(context)差不多多少,只是外面强转了下RequestManager类返回子类GlideRequests,具体差别可以事后自己看下。
这次具体分析的是Glide.with(context),定位到最后我们可以找到
@NonNull
public RequestManager get(@NonNull 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
// Only unwrap a ContextWrapper if the baseContext has a non-null application context.
// Context#createPackageContext may return a Context without an Application instance,
// in which case a ContextWrapper may be used to attach one.
&& ((ContextWrapper) context).getBaseContext().getApplicationContext() != null) {
return get(((ContextWrapper) context).getBaseContext());
}
}
return getApplicationManager(context);
}
由于ApplicationContext 和ContextWrapper这种不是常见的情况,暂且不细究(这个地方就是我说的不要被细枝末节影响了大局观,这个地方先记着,秋后算账),无论怎么走,最后会调用到
@NonNull
private RequestManager supportFragmentGet(
@NonNull Context context,
@NonNull FragmentManager fm,
@Nullable Fragment parentHint,
boolean isParentVisible) {
SupportRequestManagerFragment current =
getSupportRequestManagerFragment(fm, parentHint, isParentVisible);
RequestManager requestManager = current.getRequestManager();
if (requestManager == null) {
// TODO(b/27524013): Factor out this Glide.get() call.
Glide glide = Glide.get(context);
requestManager =
factory.build(
glide, current.getGlideLifecycle(), current.getRequestManagerTreeNode(), context);
current.setRequestManager(requestManager);
}
return requestManager;
}
意思很简单,根据FragmentManager取得对应的Fragment,暂时不用了解太多,这个时候我们知道当with的时候会有一个跟Activity绑定的SupportRequestManagerFragment,他会绑定到相应的布局之上。也就是当Activity走相应的生命周期的时候,这个fragment的生命周期也会相应的回调 ,但是这个时候还没有与请求绑定,别急 继续往下看,
之后找到GlideRequest的load方法,在RequestManager里面会找到
public RequestBuilder<Drawable> load(@Nullable String string) {
return asDrawable().load(string);
}
asDrawable()方法里返回一个RequestBuilder对象,
里面继续找
@NonNull
private RequestBuilder<TranscodeType> loadGeneric(@Nullable Object model) {
this.model = model;
isModelSet = true;
return this;
}
到这load就结束了,稍微总结下,load方法最后new一个RequestBuilder对象,对象中包含着Drawable.class
接下来就是最重要的也是最复杂的一部,into(view)
@NonNull
public ViewTarget<ImageView, TranscodeType> into(@NonNull ImageView view) {
Util.assertMainThread();
Preconditions.checkNotNull(view);
BaseRequestOptions<?> requestOptions = this;
if (!requestOptions.isTransformationSet()
&& requestOptions.isTransformationAllowed()
&& view.getScaleType() != null) {
// Clone in this method so that if we use this RequestBuilder to load into a View and then
// into a different target, we don't retain the transformation applied based on the previous
// View's scale type.
switch (view.getScaleType()) {
case CENTER_CROP:
requestOptions = requestOptions.clone().optionalCenterCrop();
break;
case CENTER_INSIDE:
requestOptions = requestOptions.clone().optionalCenterInside();
break;
case FIT_CENTER:
case FIT_START:
case FIT_END:
requestOptions = requestOptions.clone().optionalFitCenter();
break;
case FIT_XY:
requestOptions = requestOptions.clone().optionalCenterInside();
break;
case CENTER:
case MATRIX:
default:
// Do nothing.
}
}
//transcodeClass就是原来RequestBuilder的asDrawable传过来的Drawable.class
return into(
glideContext.buildImageViewTarget(view, transcodeClass),
/*targetListener=*/ null,
requestOptions,
Executors.mainThreadExecutor());
}
这个方法成功的让ImageView转化成ImageViewTarget<Drawable>
@NonNull
@Synthetic
<Y extends Target<TranscodeType>> Y into(
@NonNull Y target,
@Nullable RequestListener<TranscodeType> targetListener,
Executor callbackExecutor) {
return into(target, targetListener, /*options=*/ this, callbackExecutor);
}
private <Y extends Target<TranscodeType>> Y into(
@NonNull Y target,
@Nullable RequestListener<TranscodeType> targetListener,
BaseRequestOptions<?> options,
Executor callbackExecutor) {
Preconditions.checkNotNull(target);
if (!isModelSet) {
throw new IllegalArgumentException("You must call #load() before calling #into()");
}
Request request = buildRequest(target, targetListener, options, callbackExecutor);
Request previous = target.getRequest();
requestManager.clear(target);
target.setRequest(request);
requestManager.track(target, request);
return target;
}
方法很长,但是关键性代码其实不多,用target等参数初始化一个request对象之后,request.track方法
synchronized void track(@NonNull Target<?> target, @NonNull Request request) {
targetTracker.track(target);
requestTracker.runRequest(request);
}
这两个方法分工明确,一个是跟踪生命周期,一个是执行request命令,真正的请求。
分析targetTracker.track(target) 之前,我们先稍作休息,重新回顾一下之前源码的东西。
glide.with 会新建一个supportFragment 这个fragment与Activity绑定,而且这个fragment有一个RequestManager 也就是他们是一对一的关系,
fragment 里面有个ActivityFragmentLifecycle管理着生命周期,在requestManager初始化的时候这个lifecycle参数就是从supportFragment传进去的,
RequestManager(
Glide glide,
Lifecycle lifecycle,
RequestManagerTreeNode treeNode,
RequestTracker requestTracker,
ConnectivityMonitorFactory factory,
Context context) {
this.glide = glide;
this.lifecycle = lifecycle;
this.treeNode = treeNode;
this.requestTracker = requestTracker;
this.context = context;
connectivityMonitor =
factory.build(
context.getApplicationContext(),
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()) {
mainHandler.post(addSelfToLifecycle);
} else {
lifecycle.addListener(this);
}
lifecycle.addListener(connectivityMonitor);
defaultRequestListeners =
new CopyOnWriteArrayList<>(glide.getGlideContext().getDefaultRequestListeners());
setRequestOptions(glide.getGlideContext().getDefaultRequestOptions());
glide.registerRequestManager(this);
}
在RequestManager构造方法中,lifecycle.addListener(this); 在这个时候RequestManager的lifecycleListener与SupportFragment的lifecycleListener有了联动关系,
SupportRequestFragment
@Override
public void onStart() {
super.onStart();
lifecycle.onStart();
}
ActivityFragmentLifecycle
void onStart() {
isStarted = true;
for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
lifecycleListener.onStart();
}
}
理解了这个接下来就好理解多了,那targetTracker.track(target);就是将target加到一个Set中,之后在RequestManager接收到onstart onDestory的时候,就会直接调用target中对应回调方法。IamgeViewTarget中的回调可以看看,做了动画的开启和停止操作。
这篇博客到此就结束了,这篇如果跟着我的思路来看的话会少很多弯路,导致虽然再看,但是看得云里雾里的感觉,有了目标思路就会很清晰,下一篇会接着分析Glide缓存及请求。