当前位置:网站首页>Glide监听Activity生命周期源码分析
Glide监听Activity生命周期源码分析
2022-08-10 22:13:00 【AD钙奶-lalala】
为了分析Glide源码,我们需要先引入Glide。新建一个项目,在app.build里面引入:
dependencies {
implementation 'androidx.appcompat:appcompat:1.3.0'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
implementation 'com.github.bumptech.glide:glide:3.7.0' //Glide
}
Glide基本用法:
Glide.with(this).load(url).into(imageView);
Glide的基本用法就不讲了,我们先来看Glide.with方法:
public static RequestManager with(Activity activity) {
RequestManagerRetriever retriever = RequestManagerRetriever.get();
return retriever.get(activity);
}
RequestManager可以理解为Glide的管理类,而RequestManagerRetriever可以理解为管理RequestManager的类。我们来看下retriever的英文意思:
我们进上面的方法第一个get看下:
public static RequestManagerRetriever get() {
return INSTANCE;
}
再来看下这个INSTANCE是什么东西?
private static final RequestManagerRetriever
INSTANCE = new RequestManagerRetriever();
很明显,这是一个单例。
我们再进第二个get里面看下实现:
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public RequestManager get(Activity activity) {
if (Util.isOnBackgroundThread() ||
Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
return get(activity.getApplicationContext());
} else {
assertNotDestroyed(activity);
android.app.FragmentManager fm = activity.getFragmentManager();
return fragmentGet(activity, fm);
}
}
if语句里面的判断条件意思是后台线程或者SDK版本号小于11,所以我们关注else里面代码。
断言activity没有被销毁,获取activity的FragmentManager,将activity和fm作为参数传到fragmentGet方法中:
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
RequestManager fragmentGet(Context context,
android.app.FragmentManager fm) {
RequestManagerFragment current = getRequestManagerFragment(fm);//1
RequestManager requestManager = current.getRequestManager();
if (requestManager == null) {
requestManager = new RequestManager(context,
current.getLifecycle(), current.getRequestManagerTreeNode());
current.setRequestManager(requestManager);
}
return requestManager;
}
先来看注释1:
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
RequestManagerFragment getRequestManagerFragment(
final android.app.FragmentManager fm) {
RequestManagerFragment current =
(RequestManagerFragment) fm.findFragmentByTag(FRAGMENT_TAG);
if (current == null) {
current = pendingRequestManagerFragments.get(fm);
if (current == null) {
current = new RequestManagerFragment();
pendingRequestManagerFragments.put(fm, current);
fm.beginTransaction()
.add(current, FRAGMENT_TAG).commitAllowingStateLoss();
handler
.obtainMessage(ID_REMOVE_FRAGMENT_MANAGER, fm).sendToTarget();
}
}
return current;
}
先来通过Tag找这个Fragment,如果没找到,再去pending~里面找(HashMap),如果还没有找到,就创建一个对象,然后加到activity里面。
来看RequestManagerFragment:
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class RequestManagerFragment extends Fragment {
private final ActivityFragmentLifecycle lifecycle;
private RequestManager requestManager;
···
public RequestManagerFragment() {
this(new ActivityFragmentLifecycle());
}
// For testing only.
@SuppressLint("ValidFragment")
RequestManagerFragment(ActivityFragmentLifecycle lifecycle) {
this.lifecycle = lifecycle;
}
/**
* Sets the current {@link com.bumptech.glide.RequestManager}.
*
* @param requestManager The request manager to use.
*/
public void setRequestManager(RequestManager requestManager) {
this.requestManager = requestManager;
}
ActivityFragmentLifecycle getLifecycle() {
return lifecycle;
}
/**
* Returns the current {@link com.bumptech.glide.RequestManager} or null if none exists.
*/
public RequestManager getRequestManager() {
return requestManager;
}
@Override
public void onStart() {
super.onStart();
lifecycle.onStart();
}
@Override
public void onStop() {
super.onStop();
lifecycle.onStop();
}
@Override
public void onDestroy() {
super.onDestroy();
lifecycle.onDestroy();
}
···
}
只保留了一些核心代码,一起来看下这些核心代码解释。
我们再来重点看RequestManager的构造方法:
new RequestManager(context,
current.getLifecycle(), current.getRequestManagerTreeNode());
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 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);//1
}
lifecycle.addListener(connectivityMonitor);
}
传入了此Fragment的lifecycle,很明显这个lifecycle就是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(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();
}
}
}
我们来理一理:Glide.with()里面传入一个activity,with方法里面先通过单例获取一个RequestManagerRetriever对象,然后通过这个对象的get方法获取一个RequestManager对象。
而RequestManager初始化的时候传入的Lifecycle对象会调用addListener将RequestManager传入。我们来看RequestManagerFragment的生命周期里面调用:
@Override
public void onStart() {
super.onStart();
lifecycle.onStart();
}
@Override
public void onStop() {
super.onStop();
lifecycle.onStop();
}
@Override
public void onDestroy() {
super.onDestroy();
lifecycle.onDestroy();
}
每当fragment这几个生命周期触发的时候,就会调用ActivityFragmentLifecycle的对应方法。
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();
}
}
这里面有调用了LifecycleListener的对应方法,典型的接口回调。Util.getSnapshot代码:
public static <T> List<T> getSnapshot(Collection<T> other) {
List<T> result = new ArrayList<T>(other.size());
for (T item : other) {
result.add(item);
}
return result;
}
将Set转化成集合,其实目前的使用来看这个集合就一个对象,就是RequestManager对象。我们才想RequestManager肯定实现了LifecycleListener接口:
RequestManager implements LifecycleListener
@Override
public void onStart() {
resumeRequests();
}
@Override
public void onStop() {
pauseRequests();
}
@Override
public void onDestroy() {
requestTracker.clearRequests();
}
来做一个总结吧:通过Glide.with(Activity activity)会获取一个RequestManager对象,具体with方法是这样的:先通过单例获取一个RequestManagerRetriever,然后调用这个对象的get方法返回一个RequestManager对象,这个get方法里面又获取了activity的FragmentManager,然后又将activity和这个fm传入fragmentGet方法中,这个fragmentGet里面创建了一个无界面的fragment,然后这个fargment里面持有ActivityFragmentLifecycle,这个lifecycle就监听了无界面fragment的生命周期。fragmentGet里面还做了一件事,就是将这个获取到的fragment再拿到这个fragment的lifecycle,传入RequestManager构造并返回RequestManager对象。RequestManager构造里面有一个lifecycle.addListener方法很重要,将RequestManager对象本身传入。这样fragment生命周期变化->lifecyle对应方法触发->lifecycleListener接口回调->lifecycleListener接口实现类RequestManager对应方法触发。
边栏推荐
猜你喜欢
QT笔记——vs + qt 创建一个带界面的 dll 和 调用带界面的dll
August 10, 2022: Building Web Applications for Beginners with ASP.NET Core -- Creating Web UIs with ASP.NET Core
C # Hex file transfer skills necessary article 】 【 bin file code implementation
camera预览流程 --- 从HAL到OEM
Power system power flow calculation (Newton-Raphson method, Gauss-Seidel method, fast decoupling method) (Matlab code implementation)
2022年8月10日:使用 ASP.NET Core 为初学者构建 Web 应用程序--使用 ASP.NET Core 创建 Web UI(没看懂需要再看一遍)
68:第六章:开发文章服务:1:内容梳理;article表介绍;创建【article】文章服务;
翻译科技论文,俄译中怎样效果好
A shell script the for loop statements, while statement
Service - DNS forward and reverse domain name resolution service
随机推荐
音乐播放器(未完成版本)
uni-app微信小程序——下拉多选框
How does the Weiluntong touch screen display the current value of abnormal data while alarming?
RK3399平台开发系列讲解(内核驱动外设篇)6.35、IAM20680陀螺仪介绍
"DevOps Night Talk" - Pilot - Introduction to CNCF Open Source DevOps Project DevStream - feat. PMC member Hu Tao
JS中使用正则表达式g模式和非g模式的区别
SDP
shell programming without interaction
Nodes in the linked list are flipped in groups of k
68:第六章:开发文章服务:1:内容梳理;article表介绍;创建【article】文章服务;
解码2022中国网安强星丨正向建、反向查,华为构建数字化时代的网络安全防线
The Thread State,
阿里云新增三大高性能计算解决方案,助力生命科学行业快速发展
gcc492 compile `.rodata‘ can not be used when making a PIE object; recompile with -fPIE
STL-deque
FPGA - Memory Resources of 7 Series FPGA Internal Structure -03- Built-in Error Correction Function
Common interview questions for APP UI automation testing, maybe useful~
Thread State 详解
Research on multi-element N-k fault model of power system based on AC power flow (implemented by Matlab code) [Power System Fault]
IM 即时通讯开发如何设计图片文件的服务端存储架构