Glide源码分析其二:生命周期管理

96
美乃滋酱啊
2016.07.27 15:33* 字数 824

欢迎收看:Glide源码分析其一:基本流程

Glide****的生命周期的实现主要是通过创建一个****Fragment进行实现的

在****Glide.with(context)****这段代码中****Glide****会创建一个****RequestManager****类。该类是实现生命周期的关键方法

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;

下面是获取RequestManager的方法:

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的对象,我们来看这个类:

public class RequestManagerFragment extends Fragment {
    private final ActivityFragmentLifecycle lifecycle;
    private final RequestManagerTreeNode requestManagerTreeNode = new FragmentRequestManagerTreeNode();
    private RequestManager requestManager;
    private final HashSet<RequestManagerFragment> childRequestManagerFragments
        = new HashSet<RequestManagerFragment>();
    private RequestManagerFragment rootRequestManagerFragment;

其中的ActivityFragmentLifecycle实现了Lifecycle,根据Lifecycle的注释:

A {@link com.bumptech.glide.manager.Lifecycle} implementation for tracking and notifying listeners of {@link android.app.Fragment} and {@link android.app.Activity} lifecycle events.

可知,这个接口用于实现Activity或者Fragment的生命周期的回调

RequestManagerFragment

onAttach()

 @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        rootRequestManagerFragment = RequestManagerRetriever.get()
                .getRequestManagerFragment(getActivity().getFragmentManager());
        if (rootRequestManagerFragment != this) {
            rootRequestManagerFragment.addChildRequestManagerFragment(this);
        }
    }

先获取到root,如果当前获取的root不等于当前的管理的Fragment,则添加到当前管理类中的一个set结合中(实际上,RequestManagerFragment既充当了一个Fragment来组织生命周期的回调,同样也是一个管理者的角色,他管理了依附于不同fragmentActivty和Activity的fragment)。

那么当该fragment在销毁的时候,会执行到onDetach()放方法,直接将自己销毁:

@Override
    public void onDetach() {
        super.onDetach();
        if (rootRequestManagerFragment != null) {
            rootRequestManagerFragment.removeChildRequestManagerFragment(this);
            rootRequestManagerFragment = null;
        }
    }

值得注意的是,Glide会在actiivty进行重新创建的时候,可能因为内存不够而无法创建时,回调onLowMemory:

 @Override
    public void onLowMemory() {
        super.onLowMemory();
        // If an activity is re-created, onLowMemory may be called before a manager is ever set.
        // See #329.
        if (requestManager != null) {
            requestManager.onLowMemory();
        }
    }

lifecycle的注入

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

我们知道,在每次创建SupportRequestManagerFragment的时候,均需要一个fm作为参数,而该fm会根据一个TAG获取fragment,这样,不同的activity中的Imageview在创Glide请求的时候,会创建不同的SupportRequestManagerFragment对象,并且,我们看到SupportRequestManagerFragment的构造方法:

public SupportRequestManagerFragment() {
        this(new ActivityFragmentLifecycle());
    }

    // For testing only.
    @SuppressLint("ValidFragment")
    public SupportRequestManagerFragment(ActivityFragmentLifecycle lifecycle) {
        this.lifecycle = lifecycle;
    }

可以看见,每个不用的activity中创建的fragment会拥有自己的生命周期。

接下来,我们看上面RequestManagerFragment中的其他的生命周期的回调是在何种时候进行回调的。

1、经过前文的分析,我们知道,Glide.with(context)会创建一个RequestManager对象,该对象

requestManager = new RequestManager(context, current.getLifecycle(), current.getRequestManagerTreeNode());

中已经set进去了管理生命周期的RequestManagerfragment的lifecycle的对象。

2、那么我们就继续朝着api的调用方向:load(string)继续向下看

 public DrawableTypeRequest<String> load(String string) {
        return (DrawableTypeRequest<String>) fromString().load(string);
    }

首先创建一个DrawableTypeRequest对象,该对象,会被RequestManager注入Lifecycle:

return optionsApplier.apply(
                new DrawableTypeRequest<T>(modelClass, streamModelLoader, fileDescriptorModelLoader, context,
                        glide, requestTracker, lifecycle, optionsApplier));

这里很厉害的一个地方就是:optionsApplier.apply会把optionsApplier自己注入进去,这样,

public <Y extends Target<TranscodeType>> Y into(Y target) {

        ...
        
        Request request = buildRequest(target);
        
        /** setTag **/
        target.setRequest(request);
        lifecycle.addListener(target);
        requestTracker.runRequest(request);

        return target;
    }

中的lifecycle即为上面requestManager传递过去。

3、RequestTracker
该类是真正起到保证fragment的生命周期和进行图片资源请求的生命周期的桥梁。

RequestManager中的其他生命周期代码可知:

  • onStart()
    /**
     * Lifecycle callback that registers for connectivity events (if the android.permission.ACCESS_NETWORK_STATE
     * permission is present) and restarts failed or paused requests.
     */
    @Override
    public void onStart() {
        // onStart might not be called because this object may be created after the fragment/activity's onStart method.
        resumeRequests();
    }

其中追踪resumeRequests()是:

/**
     * Restarts any loads that have not yet completed.
     *
     * @see #isPaused()
     * @see #pauseRequests()
     */
    public void resumeRequests() {
        Util.assertMainThread();
        requestTracker.resumeRequests();
    }

最终的执行者是requestTracker,调用该段代码会将

 isPaused = false;

这样,在接下来的进行请求或者重新请求时,会依据这个标志位进行判断。

其他的生命周期也是这样子的,就不一一说了。

****最后,说明如何进行参数****requestTracker的传递的

即为上面:

创建一个DrawableTypeRequest对象,该对象,会被RequestManager注入Lifecycle,

return optionsApplier.apply(
                new DrawableTypeRequest<T>(modelClass, streamModelLoader, fileDescriptorModelLoader, context,
                        glide, requestTracker, lifecycle, optionsApplier));

同时,requestTracker也会被传入进去,这样,所有的都已经串通了,Glide的生命周期就是这样了。

Android