Glide源码分析(上)

先来看看Glide基本使用

Glide.with(mContext).load(mUrl).into(imageView);

那么我们就从with方法开始入手,with方法可以传入Context,Fragment,Activity等

// Glide类的with方法
public static RequestManager with(Context context) {
    RequestManagerRetriever retriever = RequestManagerRetriever.get();
    return retriever.get(context);
}
// RequestManagerRetriever类的get方法
public RequestManager get(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) {
            // (1)调用get方法,参数是FragmentActivity
            return get((FragmentActivity) context);
        } else if (context instanceof Activity) {
            return get((Activity) context);
        } else if (context instanceof ContextWrapper) {
            return get(((ContextWrapper) context).getBaseContext());
        }
    }
    // (2)如果当前的Context是Application Context或者不是处于主线程时
    // 返回的是getApplicationManager
    return getApplicationManager(context);
}
// 先看(2)的代码
// 这段代码单例模式创建了一个全局的applicationManager
// 因此结论是,如果Context是ApplicationContext又或者不是处于主线程时,Glide会创建一个全局的ApplicationManager
// 这个ApplicationManager的生命周期和App的生命周期一致,比较长,并且全局唯一。
private RequestManager getApplicationManager(Context context) {
    // Either an application context or we're on a background thread.
    if (applicationManager == null) {
        synchronized (this) {
            if (applicationManager == null) {
                // Normally pause/resume is taken care of by the fragment we add to the fragment or activity.
                // However, in this case since the manager attached to the application will not receive lifecycle
                // events, we must force the manager to start resumed using ApplicationLifecycle.
                applicationManager = new RequestManager(context.getApplicationContext(),
                        new ApplicationLifecycle(), new EmptyRequestManagerTreeNode());
            }
        }
    }

    return applicationManager;
}
// 接着看(1)里的代码,看是如何创建RequestManager
public RequestManager get(FragmentActivity activity) {
    if (Util.isOnBackgroundThread()) {
        return get(activity.getApplicationContext());
    } else {
        assertNotDestroyed(activity);
        FragmentManager fm = activity.getSupportFragmentManager();
        return supportFragmentGet(activity, fm);
    }
}

// supportFragmentGet方法
RequestManager supportFragmentGet(Context context, FragmentManager fm) {
    // (3)获取一个自定义的Fragment
    SupportRequestManagerFragment current = getSupportRequestManagerFragment(fm);
    RequestManager requestManager = current.getRequestManager();
    if (requestManager == null) {
        // 在RequestManager里,将Fragment的生命周期和RequestManager生命周期绑定
        requestManager = new RequestManager(context, current.getLifecycle(), current.getRequestManagerTreeNode());
        current.setRequestManager(requestManager);
    }
    return requestManager;
}

// 这段代码并不复杂,就是通过当前页面的FragmentManager去找,看有没有我们已经添加的Framgent,
// 如果没有,就new一个无界面的Fragment添加进去
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;
}
// RequestManager类的几个生命周期方法
/**
 * 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();
}

/**
 * Lifecycle callback that unregisters for connectivity events (if the android.permission.ACCESS_NETWORK_STATE
 * permission is present) and pauses in progress loads.
 */
@Override
public void onStop() {
    pauseRequests();
}

/**
 * Lifecycle callback that cancels all in progress requests and clears and recycles resources for all completed
 * requests.
 */
@Override
public void onDestroy() {
    requestTracker.clearRequests();
}

通过上述源码分析,可以得出以下结论。当我们with的时候传入的Context是Application Context又或者执行的是位于子线程时,就会通过单例的模式创建一个全局唯一的RequestManager,而这个ReuqestManager的生命周期和APP的生命周期一致。
当我们传入的Context非以上两种时,会创建一个无UI的Fragment添加到我们页面上,由于Fragment自己有自己的生命周期方法,因此当页面生命周期改变时,Fragment的生命周期自然也收到回调,接而通过接口的形式,回调到RequestManager里。在RequestManager里根据生命周期,去对这些请求进行处理。此外,和Application创建的RequestManager不同,这种情况下,每个页面都对应于一个无UI的Fragment,也对应一个RequestManager,从而实现了Glide的生命周期管理。总之,Glide.with实际作用就是通过RequestManager管理生命周期。

load方法

// RequestManager的load方法
public DrawableTypeRequest load(String string) {
    return (DrawableTypeRequest) fromString().load(string);
}

public DrawableTypeRequest fromString() {
    return loadGeneric(String.class);
}

private  DrawableTypeRequest loadGeneric(Class modelClass) {
    ModelLoader streamModelLoader = Glide.buildStreamModelLoader(modelClass, context);
    ModelLoader fileDescriptorModelLoader =
            Glide.buildFileDescriptorModelLoader(modelClass, context);
    if (modelClass != null && streamModelLoader == null && fileDescriptorModelLoader == null) {
        throw new IllegalArgumentException("Unknown type " + modelClass + ". You must provide a Model of a type for"
                + " which there is a registered ModelLoader, if you are using a custom model, you must first call"
                + " Glide#register with a ModelLoaderFactory for your custom model class");
    }
    // 重点在这,生成一个DrawableTypeRequest对象
    // DrawableTypeRequest是DrawableRequestBuilder的子类
    return optionsApplier.apply(
            new DrawableTypeRequest(modelClass, streamModelLoader, fileDescriptorModelLoader, context,
                    glide, requestTracker, lifecycle, optionsApplier));
}
// 最终调用了DrawableRequestBuilder的load方法
// 这里并没有做任何逻辑行为,只是把url赋值而已
public GenericRequestBuilder load(ModelType model) {
    this.model = model;
    isModelSet = true;
    return this;
}
Glide.with(context).load("").placeholder().bitmapTranform().into(image)
// 设置的placeholder、bitmapTranform等属性,其实都是在
// DrawableRequestBuilder里完成的,这个类就是一个建造者Builder模式

你可能感兴趣的:(Android源码)