关于Glide的生命周期设计是Glide的一个很大亮点,现在就来看一下Glide生命周期的实现。
在Glide源码解析这篇文章中就说过在Glide.with(context)
中就实现了生命周期管理,with
根据传入的参数有不同的实现。
//传入一个Context
public static RequestManager with(@NonNull Context context)
//传入一个activity
public static RequestManager with(@NonNull Activity activity)
//传入一个FragmentActivity
public static RequestManager with(@NonNull FragmentActivity activity)
//传入一个Fragment
public static RequestManager with(@NonNull Fragment fragment)
//传入一个View
public static RequestManager with(@NonNull View view)
虽然有这么多类型,但其实可以分为两类的。
当传入参数为ApplicationContext时,代码实现如下。
public static RequestManager with(@NonNull Context context) {
return getRetriever(context).get(context);
}
//由于传入参数是ApplicationContext,所以最终调用getApplicationManager方法。
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) {
//判断context类型是不是FragmentActivity
return get((FragmentActivity) context);
} else if (context instanceof Activity) {
//判断context类型是不是Activity
return get((Activity) context);
} else if (context instanceof ContextWrapper) {
//判断context类型是不是ContextWrapper
return get(((ContextWrapper) context).getBaseContext());
}
}
//context类型属于ApplicationContext
return getApplicationManager(context);
}
由于传入参数是ApplicationContext,所以最终调用getApplicationManager方法。
private RequestManager getApplicationManager(@NonNull Context context) {
// Either an application context or we're on a background thread.
if (applicationManager == null) {
synchronized (this) {
if (applicationManager == null) {
Glide glide = Glide.get(context.getApplicationContext());
applicationManager =
factory.build(
glide,
new ApplicationLifecycle(),
new EmptyRequestManagerTreeNode(),
context.getApplicationContext());
}
}
}
return applicationManager;
}
这里就直接创建一个ApplicationLifecycle
来管理生命周期,但ApplicationLifecycle
并不受控制,所以就无法对Glide生命周期进行管理。
以传入参数类型为Activity为例,代码实现如下。
public static RequestManager with(@NonNull Activity activity) {
return getRetriever(activity).get(activity);
}
public RequestManager get(@NonNull Activity activity) {
//如果在子线程,则不对Glide生命周期就那些管理
if (Util.isOnBackgroundThread()) {
return get(activity.getApplicationContext());
} else {
assertNotDestroyed(activity);
//拿到FragmentManager对象
android.app.FragmentManager fm = activity.getFragmentManager();
//获取fragment对象,并返回一个RequestManager 对象
return fragmentGet(
activity, fm, /*parentHint=*/ null, isActivityVisible(activity));
}
}
如果当前是在子线程,则不需要对Glide生命周期进行管理,否则将通过fragmentGet
方法创建一个fragment。
private RequestManager fragmentGet(@NonNull Context context,
@NonNull android.app.FragmentManager fm,
@Nullable android.app.Fragment parentHint,
boolean isParentVisible) {
//创建一个fragment对象
RequestManagerFragment current = getRequestManagerFragment(fm, parentHint, isParentVisible);
RequestManager requestManager = current.getRequestManager();
if (requestManager == null) {
// TODO(b/27524013): Factor out this Glide.get() call.
//防止Glide对象被异常回收
Glide glide = Glide.get(context);
//创建一个RequestManager对象
requestManager =
factory.build(
glide, current.getGlideLifecycle(), current.getRequestManagerTreeNode(), context);
current.setRequestManager(requestManager);
}
return requestManager;
}
在该方法中,通过getRequestManagerFragment
来获得一个Fragment对象。然后拿到该Fragment对应的RequestManager
对象,如果该对象为null则创建一个RequestManager
对象并将fragment中的ActivityFragmentLifecycle
对象传递给RequestManager
。先来看getRequestManagerFragment
方法的实现。
private RequestManagerFragment getRequestManagerFragment(
@NonNull final android.app.FragmentManager fm,
@Nullable android.app.Fragment parentHint,
boolean isParentVisible) {
//查找tag为FRAGMENT_TAG的fragment
RequestManagerFragment current = (RequestManagerFragment) fm.findFragmentByTag(FRAGMENT_TAG);
if (current == null) {
//从HashMap中取出fm
current = pendingRequestManagerFragments.get(fm);
if (current == null) {
//创建fragment对象
current = new RequestManagerFragment();
//当fragment嵌套fragment时才会使用,否则parentHint是null
current.setParentFragmentHint(parentHint);
if (isParentVisible) {
//开始执行请求
current.getGlideLifecycle().onStart();
}
//将fm添加到HashMap中,防止fragment的重复创建
pendingRequestManagerFragments.put(fm, current);
//添加fragment
fm.beginTransaction().add(current, FRAGMENT_TAG).commitAllowingStateLoss();
//从HashMap集合从移除fm
handler.obtainMessage(ID_REMOVE_FRAGMENT_MANAGER, fm).sendToTarget();
}
}
return current;
}
从fm中去查找tag为FRAGMENT_TAG
的fragment是否存在,如果不存在就从pendingRequestManagerFragments
这个HashMap中去取,如果没有就创建一个fragment,添加到pendingRequestManagerFragments
并且将该fragment绑定到activity,绑定成功后则从pendingRequestManagerFragments
移除fragment。这里的pendingRequestManagerFragments
主要是防止fragment重复创建(Glide生命周期管理),因为每个activity必须对应一个唯一的fragment。来看一下这个fragment的实现RequestManagerFragment
。
public class RequestManagerFragment extends Fragment {
private final ActivityFragmentLifecycle lifecycle;
public SupportRequestManagerFragment() {
this(new ActivityFragmentLifecycle());
}
public SupportRequestManagerFragment(@NonNull ActivityFragmentLifecycle lifecycle) {
this.lifecycle = lifecycle;
}
...
@NonNull
ActivityFragmentLifecycle getGlideLifecycle() {
return lifecycle;
}
...
@Override
public void onStart() {
super.onStart();
lifecycle.onStart();
}
@Override
public void onStop() {
super.onStop();
lifecycle.onStop();
}
@Override
public void onDestroy() {
super.onDestroy();
lifecycle.onDestroy();
unregisterFragmentWithRoot();
}
...
}
再回到fragmentGet
方法,fragment创建成功后,在创建RequestManager
时会传入fragment中的ActivityFragmentLifecycle
,再来看RequestManager
的实现。
public class RequestManager implements LifecycleListener,
ModelTypes<RequestBuilder<Drawable>> {
private final Runnable addSelfToLifecycle = new Runnable() {
@Override
public void run() {
lifecycle.addListener(RequestManager.this);
}
};
public RequestManager(
@NonNull Glide glide, @NonNull Lifecycle lifecycle,
@NonNull RequestManagerTreeNode treeNode, @NonNull Context context) {
this(
glide,
lifecycle,
treeNode,
new RequestTracker(),
glide.getConnectivityMonitorFactory(),
context);
}
// Our usage is safe here.
@SuppressWarnings("PMD.ConstructorCallsOverridableMethod")
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;
...
if (Util.isOnBackgroundThread()) {
//当在子线程时通过Handler将当前对象注册到ActivityFragmentLifecycle
mainHandler.post(addSelfToLifecycle);
} else {
//将当前对象注册到ActivityFragmentLifecycle
lifecycle.addListener(this);
}
//网络变化监听
lifecycle.addListener(connectivityMonitor);
...
}
//开始加载
@Override
public synchronized void onStart() {
resumeRequests();
//如果有动画则开始动画
targetTracker.onStart();
}
//停止加载
@Override
public synchronized void onStop() {
pauseRequests();
//如果有动画则动画停止
targetTracker.onStop();
}
//销毁
@Override
public synchronized void onDestroy() {
//如果有动画则动画结束并销毁
targetTracker.onDestroy();
...
}
//开始请求数据
synchronized void track(@NonNull Target<?> target, @NonNull Request request) {
targetTracker.track(target);
requestTracker.runRequest(request);
}
...
}
可以看见在RequestManager
的构造函数将RequestManager
注册到ActivityFragmentLifecycle
中,再来看看ActivityFragmentLifecycle
的实现。
class ActivityFragmentLifecycle implements Lifecycle {
private final Set<LifecycleListener> lifecycleListeners =
Collections.newSetFromMap(new WeakHashMap<LifecycleListener, Boolean>());
private boolean isStarted;
private boolean isDestroyed;
@Override
public void addListener(@NonNull LifecycleListener listener) {
lifecycleListeners.add(listener);
if (isDestroyed) {
listener.onDestroy();
} else if (isStarted) {
listener.onStart();
} else {
listener.onStop();
}
}
@Override
public void removeListener(@NonNull LifecycleListener listener) {
lifecycleListeners.remove(listener);
}
//每个RequestManager对应一个LifecycleListener
void onStart() {
isStarted = true;
for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
lifecycleListener.onStart();
}
}
//每个RequestManager对应一个LifecycleListener
void onStop() {
isStarted = false;
for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
lifecycleListener.onStop();
}
}
//每个RequestManager对应一个LifecycleListener
void onDestroy() {
isDestroyed = true;
for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
lifecycleListener.onDestroy();
}
}
}
由于ActivityFragmentLifecycle
对象是在fragment中创建并且它的onStart、onStop、onDestory
方法与fragment一一对应,这样就将RequestManager
的生命周期就与fragment关联起来了,也就与当前activity关联起来。总体流程如下:
当fragment生命周期发生变化时,通过ActivityFragmentLifecycle
将变化告诉给RequestManager
与DefaultConnectivityMonitor
。而RequestManager
又将此变化告诉给ImageViewTarget
。
至于传入参数为其他类型的实现基本上与activity的类似,就不在叙述。
【参考资料】
Glide生命周期管理
Glide源码分析(一) 图片加载的生命周期