在Glide解析一:Glide整體流程中,我們知道RequestManager是主要用來管理、啟動(dòng)圖片加載請(qǐng)求的。而它是通過RequestManagerRetriever創(chuàng)建、獲取的。
1、為什么用RequestManagerRetriever來獲取RequestManager?
RequestManagerRetriever.java
為什么用RequestManagerRetriever來獲取RequestManager?而不直接使用RequestManager的單例?我們通過常用的使用方式來分析其原因:
public RequestManager get(@NonNull View view) {
if (Util.isOnBackgroundThread()) {
//如果是在非UI線程,則使用綁定Application生命周期的RequestManager
return get(view.getContext().getApplicationContext());
}
Preconditions.checkNotNull(view);
Preconditions.checkNotNull(view.getContext(),
"Unable to obtain a request manager for a view without a Context");
//根據(jù)view拿到activity
Activity activity = findActivity(view.getContext());
// The view might be somewhere else, like a service.
if (activity == null) {
return get(view.getContext().getApplicationContext());
}
// Support Fragments.
// Although the user might have non-support Fragments attached to FragmentActivity, searching
// for non-support Fragments is so expensive pre O and that should be rare enough that we
// prefer to just fall back to the Activity directly.
//如果使用的是support中的activity
if (activity instanceof FragmentActivity) {
//如果是FragmentActivity
//如果view是support fragment中的,則根據(jù)view獲取其所在的support fragment,接著調(diào)用get(fragment)
//如果view是FragmentActivity中,則調(diào)用get(FragmentActivity)方法
Fragment fragment = findSupportFragment(view, (FragmentActivity) activity);
return fragment != null ? get(fragment) : get(activity);
}
//如果沒有support中的組件,其原理與support中的activity一樣,不展開講解
// Standard Fragments.
android.app.Fragment fragment = findFragment(view, activity);
if (fragment == null) {
return get(activity);
}
return get(fragment);
}
private Fragment findSupportFragment(@NonNull View target, @NonNull FragmentActivity activity) {
//清空view和fragment關(guān)聯(lián)列表
tempViewToSupportFragment.clear();
//從activity的所有fragment中找出fragment的根view,并將根view與fragment進(jìn)行關(guān)聯(lián)存放view和fragment關(guān)聯(lián)列表tempViewToSupportFragment中
findAllSupportFragmentsWithViews(
activity.getSupportFragmentManager().getFragments(), tempViewToSupportFragment);
Fragment result = null;
View activityRoot = activity.findViewById(android.R.id.content);
View current = target;
while (!current.equals(activityRoot)) {
//從view和fragment關(guān)聯(lián)列表中獲取view所關(guān)聯(lián)的fragment
result = tempViewToSupportFragment.get(current);
if (result != null) {
break;
}
if (current.getParent() instanceof View) {
//獲取當(dāng)前view的父級(jí)view
current = (View) current.getParent();
} else {
break;
}
}
tempViewToSupportFragment.clear();
return result;
}
private static void findAllSupportFragmentsWithViews(
@Nullable Collection<Fragment> topLevelFragments,
@NonNull Map<View, Fragment> result) {
if (topLevelFragments == null) {
return;
}
for (Fragment fragment : topLevelFragments) {
//遍歷fragment
// getFragment()s in the support FragmentManager may contain null values, see #1991.
if (fragment == null || fragment.getView() == null) {
continue;
}
//將fragment的根view與fragment進(jìn)行關(guān)聯(lián)
result.put(fragment.getView(), fragment);
findAllSupportFragmentsWithViews(fragment.getChildFragmentManager().getFragments(), result);
}
}
一般我們都是使用support 中的fragmetactivity,所以get(view)要么轉(zhuǎn)到get(Fragment)中要么轉(zhuǎn)到get(FragmentActivity)中。這里先根據(jù)view找到其所在fragment的思路是拿當(dāng)前view的根view與activity的所有fragment的根view進(jìn)行比較,如果相等,則這個(gè)fragment就是我們要找的fragment。
1.1、get(Fragment) 的實(shí)現(xiàn)邏輯
public RequestManager get(@NonNull Fragment fragment) {
//...
//獲取fragment的子FragmentManager
FragmentManager fm = fragment.getChildFragmentManager();
//調(diào)用supportFragmentGet
return supportFragmentGet(fragment.getActivity(), fm, fragment, fragment.isVisible());
}
}
private RequestManager supportFragmentGet(
@NonNull Context context,
@NonNull FragmentManager fm,
@Nullable Fragment parentHint,
boolean isParentVisible) {
//根據(jù)FragmentManager獲取已經(jīng)存在的SupportRequestManagerFragment 或者創(chuàng)建一個(gè)新的SupportRequestManagerFragment
SupportRequestManagerFragment current =
getSupportRequestManagerFragment(fm, parentHint, isParentVisible);
//獲取與fragment關(guān)聯(lián)的RequestManager
RequestManager requestManager = current.getRequestManager();
if (requestManager == null) {
// TODO(b/27524013): Factor out this Glide.get() call.
//RequestManager為空
Glide glide = Glide.get(context);
//構(gòu)建一個(gè)新的RequestManager
requestManager =
factory.build(
glide, current.getGlideLifecycle(), current.getRequestManagerTreeNode(), context);
//將fragment與RequestManager進(jìn)行關(guān)聯(lián)
current.setRequestManager(requestManager);
}
return requestManager;
}
get(Fragment)獲取SupportRequestManagerFragment 的邏輯我們看下其代碼實(shí)現(xiàn):
private SupportRequestManagerFragment getSupportRequestManagerFragment(
@NonNull final FragmentManager fm, @Nullable Fragment parentHint, boolean isParentVisible) {
//根據(jù)tag名稱從FragmentManager中查找SupportRequestManagerFragment
SupportRequestManagerFragment current =
(SupportRequestManagerFragment) fm.findFragmentByTag(FRAGMENT_TAG);
if (current == null) {
//如果FragmentManager沒有SupportRequestManagerFragment
//從等待FragmentManager添加Fragment完成列表中獲取SupportRequestManagerFragment
current = pendingSupportRequestManagerFragments.get(fm);
if (current == null) {
////如果沒有SupportRequestManagerFragment
//創(chuàng)建新的SupportRequestManagerFragment
current = new SupportRequestManagerFragment();
//將新創(chuàng)建的fragment加到其父級(jí)fragment列表中
current.setParentFragmentHint(parentHint);
if (isParentVisible) {
//如果父級(jí)可見,回調(diào)生命周期的onStart
current.getGlideLifecycle().onStart();
}
//將創(chuàng)建的fragment加入等待FragmentManager添加fragment的隊(duì)列中
pendingSupportRequestManagerFragments.put(fm, current);
//將創(chuàng)建的fragment加入FragmentManager中
fm.beginTransaction().add(current, FRAGMENT_TAG).commitAllowingStateLoss();
//發(fā)送消息,從等待FragmentManager添加fragment的隊(duì)列中刪除fragment
handler.obtainMessage(ID_REMOVE_SUPPORT_FRAGMENT_MANAGER, fm).sendToTarget();
}
}
return current;
}
根據(jù)上面的代碼分析可以歸納RequestManagerRetriever創(chuàng)建或者獲取RequestManager的流程:
- 如果在子線程,則創(chuàng)建一個(gè)生命周期與Application一樣的RequestManager
- 根據(jù)view先拿到其所屬的fragment或者activity
- 從當(dāng)前framgnet或者activity中獲取RequestManagerFragment,如果不為空則返回與之關(guān)聯(lián)的RequestManager;如果為空那么創(chuàng)建一個(gè)新的RequestManagerFragment,創(chuàng)建的情況下順便創(chuàng)建RequestManager,并進(jìn)行關(guān)聯(lián),并返回該RequestManager
根據(jù)這段代碼有2個(gè)問題,
問題1:為什么使用pendingSupportRequestManagerFragments來添加RequestManagerManager?fm添加RequestManagerFragment之后又發(fā)送消息刪除該RequestManagerFragment呢?
答案:因?yàn)閒m添加fragment不是調(diào)用add方法就代表添加完成的,它有相關(guān)的生命周期是異步進(jìn)行的,所以如果add之后立馬又在相同fragment或者activity環(huán)境中調(diào)用get方法,那么就很有可能又創(chuàng)建一個(gè)新的RequestManagerFragment,而pendingSupportRequestManagerFragments就是為了杜絕重復(fù)創(chuàng)建RequestManagerFragment而準(zhǔn)備的。
問題2:對(duì)于glide的get使用有什么優(yōu)化的地方嗎?
答案: - 盡量不要在子線程中調(diào)用,因?yàn)樽泳€程調(diào)用意味著生命周期是全局的,不能跟activity或fragment的生命周期同步
- get的時(shí)候最好傳activity、或者fragment,因?yàn)檫@樣可以減少查找具體的fragment或者activity的步驟
問題3:為什么要用RequestManagerFragment并與RequestManager進(jìn)行關(guān)聯(lián)呢?
答案:是為了進(jìn)行自動(dòng)感應(yīng)組件的生命周期
2、為什么要用RequestManagerFragment并與RequestManager進(jìn)行關(guān)聯(lián)?
步驟1中分析了get的流程中,fragment和activity最終是通過創(chuàng)建RequestManagerFragment并和RequestManager進(jìn)行關(guān)聯(lián)
我們看下RequestManagerFragment的幾個(gè)關(guān)鍵生命周期函數(shù):
@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();
}
RequestManagerFragment的生命周期相關(guān)的函數(shù)調(diào)用lifecycle對(duì)象對(duì)應(yīng)的方法,而lifecycle是在SupportRequestManagerFragment構(gòu)造函數(shù)數(shù)中創(chuàng)建的:
public SupportRequestManagerFragment() {
this(new ActivityFragmentLifecycle());
}
ActivityFragmentLifecycle內(nèi)部維持了生命周期的監(jiān)聽者列表:
class ActivityFragmentLifecycle implements Lifecycle {
private final Set<LifecycleListener> lifecycleListeners =
Collections.newSetFromMap(new WeakHashMap<LifecycleListener, Boolean>());
//...
}
當(dāng)RequestManagerFragment生命周期變化時(shí),調(diào)用ActivityFragmentLifecycle的對(duì)應(yīng)生命周期方法,其實(shí)現(xiàn)就是遍歷生命周期監(jiān)聽列表,并調(diào)用監(jiān)聽者對(duì)應(yīng)的生命周期方法:
void onStart() {
isStarted = true;
for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
lifecycleListener.onStart();
}
}
那么什么時(shí)候添加監(jiān)聽者到ActivityFragmentLifecycle呢?答案是創(chuàng)建RequestManager的時(shí)候,我們看下RequestManager構(gòu)成函數(shù):
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()) {
//如果是自線程,則切換到主線程監(jiān)聽生命周期
mainHandler.post(addSelfToLifecycle);
} else {
//監(jiān)聽生命周期
lifecycle.addListener(this);
}
//生命周期變化時(shí),相應(yīng)的監(jiān)聽網(wǎng)絡(luò)狀態(tài)和取消監(jiān)聽網(wǎng)絡(luò)裝
lifecycle.addListener(connectivityMonitor);
setRequestOptions(glide.getGlideContext().getDefaultRequestOptions());
glide.registerRequestManager(this);
}
ok,最后我們總結(jié)下Glide是如何自動(dòng)感應(yīng)生命周期的:
- 如果是在子線程,這Glide使用的RequestManager與Application一樣的生命周期
- 如果是fragment、activity,則使用FragmentManagerFragment與RequestManager進(jìn)行關(guān)聯(lián),通過FragmentManagerFragment的生命周期變化來調(diào)度RequestManager對(duì)圖片加載請(qǐng)求Request采取暫停、重新開始、停止等操作。
因?yàn)锳ndroid有fragment、support包中的fragment、activity、surport中的activity,因?yàn)槭褂肍ragmentManagerFragment來實(shí)現(xiàn)RequestManager感應(yīng)生命周期,這幾個(gè)fragmengt、activity使用的FragmentManager各自不同,如果是fragment在用ChildFragmentManager或者support中的ChildFragmentManager;如果是activity則用FragmentManager或者support中的FragmentManager。所以RequestManagerRetriever主要用來根據(jù)framgnet、activity來創(chuàng)建對(duì)應(yīng)的RequestManager。
問題:Glide中最多有幾個(gè)RequestManager?
答案:5個(gè),分別是: - 與Application生命周期一致的RequestManager
- 與app包下activity的FragmentManager關(guān)聯(lián)的RequestManager
- 與app包下fragment的ChildFragmentManager關(guān)聯(lián)的RequestManager
- 與support包下activity的FragmentManager關(guān)聯(lián)的RequestManager
- 與support包下fragment的ChildFragmentManager關(guān)聯(lián)的RequestManager
問題:Glide的get操作有哪些優(yōu)化點(diǎn)?
答案: - 在UI線程中調(diào)用,可以避免RequestManager生命周期與Application的一直
- 盡量采用support報(bào)下的fragment/activity;一是因?yàn)榧嫒菪裕欢侨绻y(tǒng)一使用support包下的可以避免創(chuàng)建于與app包下FragmentManager管理的RequestManager
- get盡量傳遞fragment或者activity,這樣可以減少通過view找到具體的fragment或者activity的步驟