我们直接来看Glide 是如何把网络请求与Activity/Fragment的生命周期同步的,当我们调用Glide.with()的时候,
public static RequestManager with(FragmentActivity activity) {
RequestManagerRetriever retriever = RequestManagerRetriever.get();
return retriever.get(activity);
}
--》get(activity)
publicRequestManagerget(FragmentActivity activity) {
if(Util.isOnBackgroundThread()) {
returnget(activity.getApplicationContext());
}else{
assertNotDestroyed(activity);
FragmentManager fm = activity.getSupportFragmentManager();
return supportFragmentGet(activity,fm);
}
}
--》supportFragmentGet(activity,fm);
RequestManager supportFragmentGet(Context context,FragmentManager fm) {
SupportRequestManagerFragment current = getSupportRequestManagerFragment(fm);
RequestManager requestManager = current.getRequestManager();
if(requestManager ==null) {
requestManager =newRequestManager(context,current.getLifecycle(),current.getRequestManagerTreeNode());
current.setRequestManager(requestManager);//fragment的生命周期与RequestManger绑定
}
return requestManager;
}
会有一个SupportRequestManagerFragment与Activity的生命周期绑定,并且在里面有一个ActivityFragmentLifecycle lifecycle的成员变量,SupportRequestManagerFragment的生命周期方法中调用了lifcylce的方法,如onStart(),这个时候,
public void onStart() {
super.onStart();
lifecycle.onStart();
}
就会遍历lifecycle的set<LifeCycleListener>集合,通知注册了LifecycleListener的对象,
void onStart() {
isStarted=true;
for(LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
lifecycleListener.onStart();
}
}
那谁注册了这个监听呢?那就是RequestManager,所以会调用RequestManger的onStart()方法,
public void onStart() {
// onStart might not be called because this object may be created after the fragment/activity's onStart method.
resumeRequests();
}
public void resumeRequests() {
Util.assertMainThread();
requestTracker.resumeRequests();//后面会在into()方法中requestTracker.runRequest先把request添加set中,
}
但是RequestManager 也是交给RequestTracker的resumeRequests()方法处理,
public void resumeRequests() {
isPaused=false;
for(Request request : Util.getSnapshot(requests)) {
if(!request.isComplete() && !request.isCancelled() && !request.isRunning()) {
request.begin();
}
}
pendingRequests.clear();//这个pendingRequests集合中保存了未完成的request
}
调用request.begin()方法,相当于调用了GenericRequest的onSizeReady()方法,接着调用Engine中的load()------
后面会说明glide中是如何完成整个请求。同理,取消,暂停都是同样的流程调用对应的方法而已。
一个简单的加载图片。
Glide.with(context).load(url).placeholder(s).into(imageview)
首先,with()把网络请求与生命周期联结起来了。load()把url传入了GenericRequestBuilder()赋值给model,placeholder()把把预览图片赋值给了placeholderId,into()最后组装这些参数,具体调用过程:
into(ImageView view)--》
glide.buildImageViewTarget(view,transcodeClass) 将view封装成target --》
into(Y target) 在这个方法里面 :
Request previous = target.getRequest(); // 解决了图片加载错位的问题。
if(previous !=null) {
previous.clear();
requestTracker.removeRequest(previous);
previous.recycle();
}
Request request = buildRequest(target); // 这里会调用到obtainRequest()将传入GenericRequestBuilder的参数,如model(url)封装到request中。
target.setRequest(request);//这里把request作为tag与target绑定在了一起,
lifecycle.addListener(target);//添加到了lifecyle的实现类,也就是ActivityFragmentLifecycle中的Set<LifecycleListener>中。
requestTracker.runRequest(request);
--》requestTracker.runRequest(request);
requests.add(request); //生命周期中讲到了在requestTracker中有一个集合
if(!isPaused) {
request.begin(); //在这里开始请求。
}else{
pendingRequests.add(request);
}
--》request.begin()
public void begin() {
onSizeReady(overrideWidth,overrideHeight);
if(!isComplete() && !isFailed() && canNotifyStatusChanged()) {
target.onLoadStarted(getPlaceholderDrawable());//在这里显示设置的预加载图片
}
}
--》onSizeReady()
public void onSizeReady (intwidth, intheight) {
ModelLoader modelLoader =loadProvider.getModelLoader();//DataLoadProvider接口的子类。根据model的类型,转换得到不同的ModelLoader。
final DataFetcher dataFetcher = modelLoader.getResourceFetcher(model,width,height);//得到了一个对应的加载器。如果model传入的是个null,则会得到 NullFetcher。
ResourceTranscoder transcoder =loadProvider.getTranscoder(); //这个tanscoder可以把不同类型的图片转换。
loadStatus=engine.load(signature,width,height,dataFetcher,loadProvider,transformation,transcoder
}
--》engine.load( )
public LoadStatus load(Key signature, intwidth, intheight,DataFetcher fetcher,
DataLoadProvider loadProvider,Transformation transformation,ResourceTranscoder transcoder,
Priority priority, booleanisMemoryCacheable,DiskCacheStrategy diskCacheStrategy,ResourceCallback cb) {
EngineKey key =keyFactory.buildKey()
EngineResource cached = loadFromCache(key,isMemoryCacheable);//先从内存中加载。
if(cached !=null) {
cb.onResourceReady(cached);
if(Log.isLoggable(TAG,Log.VERBOSE)) {
logWithTimeAndKey("Loaded resource from cache",startTime,key);
}
return null;
}
EngineResource active = loadFromActiveResources(key,isMemoryCacheable);//从本地加载
if(active !=null) {
cb.onResourceReady(active);
if(Log.isLoggable(TAG,Log.VERBOSE)) {
logWithTimeAndKey("Loaded resource from active resources",startTime,key);
}
return null;
}
EngineJob current =jobs.get(key);
if(current !=null) {
current.addCallback(cb);
if(Log.isLoggable(TAG,Log.VERBOSE)) {
logWithTimeAndKey("Added to existing load",startTime,key);
}
return newLoadStatus(cb,current);
}
EngineJob engineJob =engineJobFactory.build(key,isMemoryCacheable);
DecodeJob decodeJob =newDecodeJob(key,width,height,fetcher,loadProvider,transformation,
transcoder,diskCacheProvider,diskCacheStrategy,priority);
EngineRunnable runnable =newEngineRunnable(engineJob,decodeJob,priority);
jobs.put(key,engineJob);
engineJob.addCallback(cb);
engineJob.start(runnable);//从网络中加载
if(Log.isLoggable(TAG,Log.VERBOSE)) {
logWithTimeAndKey("Started new load",startTime,key);
}
return newLoadStatus(cb,engineJob);
}
--》engineJob.start(runnable); 启动 EngineRunnable
public void run() {
resource = decode();//加载资源
if(resource ==null) {
onLoadFailed(exception);//加载失败的图片
}else{
onLoadComplete(resource);//这个回调会把正确的resource如(bitmap)设置到targetz中,最终完成显示到控件上面
}
}
--》decode()
private Resource decode()throwsException {
if(isDecodingFromCache()) {
return decodeFromCache();
}else{
return decodeFromSource();/
}
}
--》decodeFromSource()
publicResourcedecodeFromSource()throwsException {
Resource decoded = decodeSource();
return transformEncodeAndTranscode(decoded);
}
--》decodeSource()
privateResourcedecodeSource()throwsException {
Resource decoded =null;
try{
longstartTime = LogTime.getLogTime();
final A data =fetcher.loadData(priority);//加载器在这里会开始加载数据,如HttpUrlFetcher 返回值是输入流
if(Log.isLoggable(TAG,Log.VERBOSE)) {
logWithTimeAndKey("Fetched data",startTime);
}
if(isCancelled) {
return null;
}
decoded = decodeFromSourceData(data);//对流进行处理,返回请求的资源,如bitmap
}finally{
fetcher.cleanup();
}
returndecoded;
}