1. 程式人生 > >Glide生命週期原碼解析

Glide生命週期原碼解析

Glide生命週期管理的原碼其實就在

Glide.with(getContext()) 這個方法裡面
 @NonNull
  public static RequestManager with(@NonNull Context context) {
    return getRetriever(context).get(context);
  }

 @NonNull
  private static RequestManagerRetriever getRetriever(@Nullable Context context) {
   
    return Glide.get(context).getRequestManagerRetriever();
  }

獲取到了一個請求管理者 RequestManagerRetriever,最終是通過工廠模式建立的

在Glide.get(context)方法中最後會執行到

initializeGlide(...) 這裡
private static void initializeGlide(@NonNull Context context, @NonNull GlideBuilder builder) {
    Context applicationContext = context.getApplicationContext();
    
    RequestManagerRetriever.RequestManagerFactory factory =
        annotationGeneratedModule != null
            ? annotationGeneratedModule.getRequestManagerFactory() : null;
    builder.setRequestManagerFactory(factory);
    
    Glide glide = builder.build(applicationContext);
    
    applicationContext.registerComponentCallbacks(glide);
    Glide.glide = glide;
  }
一些無關程式碼刪掉,這裡會對Glide賦值,而在builder.build(...)方法中,對RequestManagerRetriever進行了建立
Glide build(@NonNull Context context) {
    ...

    RequestManagerRetriever requestManagerRetriever =
        new RequestManagerRetriever(requestManagerFactory);

    return new Glide(
        context,
        engine,
        memoryCache,
        bitmapPool,
        arrayPool,
        requestManagerRetriever,
        connectivityMonitorFactory,
        logLevel,
        defaultRequestOptions.lock(),
        defaultTransitionOptions);
  }

刪除無用程式碼,一目瞭然.最後在new Glide()程式碼裡對

requestManagerRetriever 進行了賦值.

所以再貼一下之前建立requestManagerRetriever的方法

 @NonNull
  public static RequestManager with(@NonNull Context context) {
    return getRetriever(context).get(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) {
        return get(((ContextWrapper) context).getBaseContext());
      }
    }

    return getApplicationManager(context);
  }

最後通過requestManagerRetriever.get(...)方法進行了了建立一個無UI的fragment來進行生命週期的管理,這裡只分析FragmentActivity,其它的都是一樣的道理.先貼程式碼

  @NonNull
  public RequestManager get(@NonNull FragmentActivity activity) {
    if (Util.isOnBackgroundThread()) {
      return get(activity.getApplicationContext());
    } else {
      assertNotDestroyed(activity);
      FragmentManager fm = activity.getSupportFragmentManager();
      return supportFragmentGet(
          activity, fm, /*parentHint=*/ null, isActivityVisible(activity));
    }
  }

首先獲取到FragmentManager管理者,再通過 supportFragmentGet(...)方法來獲取到RequestManager類,看程式碼的註釋

@NonNull
  private RequestManager supportFragmentGet(
      @NonNull Context context,
      @NonNull FragmentManager fm,
      @Nullable Fragment parentHint,
      boolean isParentVisible) {//Activity是否銷燬

    //首先通過getSupportRequestManagerFragment(..)方法來獲取到一個fragment,
    SupportRequestManagerFragment current = getSupportRequestManagerFragment(fm, parentHint, isParentVisible);
    //通過current獲取到請求管理者,每個fragment都有一個對應的RequestManager
    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
      current.setRequestManager(requestManager);
    }
    return requestManager;//最後返回
  }

先來看看RequestManager的構造方法,這裡將生命週期監聽加入進去,並也添加了網路連線監聽和請求監聽等,所以Glidle的生命週期管理最後也就是在RequestManager類裡面來管理的.

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 (Util.isOnBackgroundThread()) {
      mainHandler.post(addSelfToLifecycle);
    } else {
      lifecycle.addListener(this);
    }
    lifecycle.addListener(connectivityMonitor);

    setRequestOptions(glide.getGlideContext().getDefaultRequestOptions());

    glide.registerRequestManager(this);
  }

再來看看建立fragment的程式碼

@NonNull
  private SupportRequestManagerFragment getSupportRequestManagerFragment(
      @NonNull final FragmentManager fm, @Nullable Fragment parentHint, boolean isParentVisible) {
    SupportRequestManagerFragment current =
        (SupportRequestManagerFragment) fm.findFragmentByTag(FRAGMENT_TAG);
    if (current == null) {
      current = pendingSupportRequestManagerFragments.get(fm);
      if (current == null) {
        current = new SupportRequestManagerFragment();
        current.setParentFragmentHint(parentHint);
        if (isParentVisible) {
          current.getGlideLifecycle().onStart();
        }
        pendingSupportRequestManagerFragments.put(fm, current);
        fm.beginTransaction().add(current, FRAGMENT_TAG).commitAllowingStateLoss();
        handler.obtainMessage(ID_REMOVE_SUPPORT_FRAGMENT_MANAGER, fm).sendToTarget();
      }
    }
    return current;
  }