privatestaticRequestManagerRetrievergetRetriever(@NullableContextcontext){// Context could be null for other reasons (ie the user passes in null), but in practice it will// only occur due to errors with the Fragment lifecycle.Preconditions.checkNotNull(context,"You cannot start a load on a not yet attached View or a Fragment where getActivity() "+"returns null (which usually occurs when getActivity() is called before the Fragment "+"is attached or after the Fragment is destroyed).");returnGlide.get(context).getRequestManagerRetriever();}
privatestaticGeneratedAppGlideModulegetAnnotationGeneratedGlideModules(Contextcontext){GeneratedAppGlideModuleresult=null;try{Class<GeneratedAppGlideModule>clazz=(Class<GeneratedAppGlideModule>)Class.forName("com.bumptech.glide.GeneratedAppGlideModuleImpl");result=clazz.getDeclaredConstructor(Context.class).newInstance(context.getApplicationContext());}catch(ClassNotFoundExceptione){if(Log.isLoggable(TAG,Log.WARN)){Log.w(TAG,"Failed to find GeneratedAppGlideModule. You should include an"+" annotationProcessor compile dependency on com.github.bumptech.glide:compiler"+" in your application and a @GlideModule annotated AppGlideModule implementation"+" or LibraryGlideModules will be silently ignored");}// These exceptions can't be squashed across all versions of Android.}catch(InstantiationExceptione){throwIncorrectGlideModule(e);}catch(IllegalAccessExceptione){throwIncorrectGlideModule(e);}catch(NoSuchMethodExceptione){throwIncorrectGlideModule(e);}catch(InvocationTargetExceptione){throwIncorrectGlideModule(e);}returnresult;}
finalclassGeneratedAppGlideModuleImplextendsGeneratedAppGlideModule{privatefinalGalleryModuleappGlideModule;publicGeneratedAppGlideModuleImpl(Contextcontext){appGlideModule=newGalleryModule();if(Log.isLoggable("Glide",Log.DEBUG)){Log.d("Glide","Discovered AppGlideModule from annotation: com.bumptech.glide.samples.gallery.GalleryModule");Log.d("Glide","Discovered LibraryGlideModule from annotation: com.bumptech.glide.integration.okhttp3.OkHttpLibraryGlideModule");}}@OverridepublicvoidapplyOptions(@NonNullContextcontext,@NonNullGlideBuilderbuilder){appGlideModule.applyOptions(context,builder);}@OverridepublicvoidregisterComponents(@NonNullContextcontext,@NonNullGlideglide,@NonNullRegistryregistry){newOkHttpLibraryGlideModule().registerComponents(context,glide,registry);appGlideModule.registerComponents(context,glide,registry);}@OverridepublicbooleanisManifestParsingEnabled(){returnappGlideModule.isManifestParsingEnabled();}@Override@NonNullpublicSet<Class<?>>getExcludedModuleClasses(){returnCollections.emptySet();}@Override@NonNullGeneratedRequestManagerFactorygetRequestManagerFactory(){returnnewGeneratedRequestManagerFactory();}}
@GuardedBy("Glide.class")privatestaticvoidcheckAndInitializeGlide(@NonNullContextcontext,@NullableGeneratedAppGlideModulegeneratedAppGlideModule){// In the thread running initGlide(), one or more classes may call Glide.get(context).// Without this check, those calls could trigger infinite recursion.if(isInitializing){thrownewIllegalStateException("You cannot call Glide.get() in registerComponents(),"+" use the provided Glide instance instead");}isInitializing=true;initializeGlide(context,generatedAppGlideModule);isInitializing=false;}
privatestaticvoidinitializeGlide(@NonNullContextcontext,@NonNullGlideBuilderbuilder,@NullableGeneratedAppGlideModuleannotationGeneratedModule){ContextapplicationContext=context.getApplicationContext();List<com.bumptech.glide.module.GlideModule>manifestModules=Collections.emptyList();//1.解析AndroidManifest.xmlif(annotationGeneratedModule==null||annotationGeneratedModule.isManifestParsingEnabled()){manifestModules=newManifestParser(applicationContext).parse();}//2.移除标注为排除的GlideModuleif(annotationGeneratedModule!=null&&!annotationGeneratedModule.getExcludedModuleClasses().isEmpty()){Set<Class<?>>excludedModuleClasses=annotationGeneratedModule.getExcludedModuleClasses();Iterator<com.bumptech.glide.module.GlideModule>iterator=manifestModules.iterator();while(iterator.hasNext()){com.bumptech.glide.module.GlideModulecurrent=iterator.next();if(!excludedModuleClasses.contains(current.getClass())){continue;}iterator.remove();}}//3.获取RequestManagerFactory即GeneratedRequestManagerFactoryRequestManagerRetriever.RequestManagerFactoryfactory=annotationGeneratedModule!=null?annotationGeneratedModule.getRequestManagerFactory():null;//为GlideBuilder设置RequestManagerFactorybuilder.setRequestManagerFactory(factory);for(com.bumptech.glide.module.GlideModulemodule:manifestModules){module.applyOptions(applicationContext,builder);}if(annotationGeneratedModule!=null){annotationGeneratedModule.applyOptions(applicationContext,builder);}//调用build方法创建Glide对象Glideglide=builder.build(applicationContext);for(com.bumptech.glide.module.GlideModulemodule:manifestModules){try{module.registerComponents(applicationContext,glide,glide.registry);}catch(AbstractMethodErrore){thrownewIllegalStateException("Attempting to register a Glide v3 module. If you see this, you or one of your"+" dependencies may be including Glide v3 even though you're using Glide v4."+" You'll need to find and remove (or update) the offending dependency."+" The v3 module name is: "+module.getClass().getName(),e);}}if(annotationGeneratedModule!=null){annotationGeneratedModule.registerComponents(applicationContext,glide,glide.registry);}applicationContext.registerComponentCallbacks(glide);Glide.glide=glide;}
<manifest...><!-- ... permissions --><application...><meta-dataandroid:name="com.mypackage.MyGlideModule"android:value="GlideModule"/><!-- ... activities and other components --></application></manifest>
Glide(@NonNullContextcontext,@NonNullEngineengine,@NonNullMemoryCachememoryCache,@NonNullBitmapPoolbitmapPool,@NonNullArrayPoolarrayPool,@NonNullRequestManagerRetrieverrequestManagerRetriever,@NonNullConnectivityMonitorFactoryconnectivityMonitorFactory,intlogLevel,@NonNullRequestOptionsFactorydefaultRequestOptionsFactory,@NonNullMap<Class<?>,TransitionOptions<?,?>>defaultTransitionOptions,@NonNullList<RequestListener<Object>>defaultRequestListeners,booleanisLoggingRequestOriginsEnabled,booleanisImageDecoderEnabledForBitmaps,inthardwareBitmapFdLimit){this.engine=engine;this.bitmapPool=bitmapPool;this.arrayPool=arrayPool;this.memoryCache=memoryCache;this.requestManagerRetriever=requestManagerRetriever;this.connectivityMonitorFactory=connectivityMonitorFactory;this.defaultRequestOptionsFactory=defaultRequestOptionsFactory;finalResourcesresources=context.getResources();registry=newRegistry();registry.register(newDefaultImageHeaderParser());// Right now we're only using this parser for HEIF images, which are only supported on OMR1+.// If we need this for other file types, we should consider removing this restriction.if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O_MR1){registry.register(newExifInterfaceImageHeaderParser());}//...//注册 这里省略了一部分注册registry.append(ByteBuffer.class,newByteBufferEncoder())//....register(GifDrawable.class,byte[].class,gifDrawableBytesTranscoder);//创建TargetFactoryImageViewTargetFactoryimageViewTargetFactory=newImageViewTargetFactory();//创建GlideContextglideContext=newGlideContext(context,arrayPool,registry,imageViewTargetFactory,defaultRequestOptionsFactory,defaultTransitionOptions,defaultRequestListeners,engine,isLoggingRequestOriginsEnabled,logLevel);}
privateRequestManagerfragmentGet(@NonNullContextcontext,@NonNullandroid.app.FragmentManagerfm,@Nullableandroid.app.FragmentparentHint,booleanisParentVisible){//创建RequestManagerFragmentRequestManagerFragmentcurrent=getRequestManagerFragment(fm,parentHint);RequestManagerrequestManager=current.getRequestManager();if(requestManager==null){// TODO(b/27524013): Factor out this Glide.get() call.Glideglide=Glide.get(context);//将Lifecycle和RequestManagerTreeNode传递给RequestManagerrequestManager=factory.build(glide,current.getGlideLifecycle(),current.getRequestManagerTreeNode(),context);// This is a bit of hack, we're going to start the RequestManager, but not the// corresponding Lifecycle. It's safe to start the RequestManager, but starting the// Lifecycle might trigger memory leaks. See b/154405040if(isParentVisible){requestManager.onStart();}current.setRequestManager(requestManager);}returnrequestManager;}
publicinterfaceLifecycle{/** Adds the given listener to the set of listeners managed by this Lifecycle implementation. */voidaddListener(@NonNullLifecycleListenerlistener);/** * Removes the given listener from the set of listeners managed by this Lifecycle implementation, * returning {@code true} if the listener was removed successfully, and {@code false} otherwise. * * <p>This is an optimization only, there is no guarantee that every added listener will * eventually be removed. */voidremoveListener(@NonNullLifecycleListenerlistener);}
publicinterfaceLifecycleListener{/** * Callback for when {@link android.app.Fragment#onStart()}} or {@link * android.app.Activity#onStart()} is called. */voidonStart();/** * Callback for when {@link android.app.Fragment#onStop()}} or {@link * android.app.Activity#onStop()}} is called. */voidonStop();/** * Callback for when {@link android.app.Fragment#onDestroy()}} or {@link * android.app.Activity#onDestroy()} is called. */voidonDestroy();}
privatefinalRunnableaddSelfToLifecycle=newRunnable(){@Overridepublicvoidrun(){lifecycle.addListener(RequestManager.this);}};privatefinalConnectivityMonitorconnectivityMonitor;// Adding default listeners should be much less common than starting new requests. We want// some way of making sure that requests don't mutate our listeners without creating a new copy of// the list each time a request is started.privatefinalCopyOnWriteArrayList<RequestListener<Object>>defaultRequestListeners;@GuardedBy("this")privateRequestOptionsrequestOptions;privatebooleanpauseAllRequestsOnTrimMemoryModerate;publicRequestManager(@NonNullGlideglide,@NonNullLifecyclelifecycle,@NonNullRequestManagerTreeNodetreeNode,@NonNullContextcontext){this(glide,lifecycle,treeNode,newRequestTracker(),glide.getConnectivityMonitorFactory(),context);}// Our usage is safe here.@SuppressWarnings("PMD.ConstructorCallsOverridableMethod")RequestManager(Glideglide,Lifecyclelifecycle,RequestManagerTreeNodetreeNode,RequestTrackerrequestTracker,ConnectivityMonitorFactoryfactory,Contextcontext){this.glide=glide;this.lifecycle=lifecycle;this.treeNode=treeNode;this.requestTracker=requestTracker;this.context=context;connectivityMonitor=factory.build(context.getApplicationContext(),newRequestManagerConnectivityListener(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()){Util.postOnUiThread(addSelfToLifecycle);}else{lifecycle.addListener(this);}//添加lifecycle.addListener(connectivityMonitor);//...}
@NonNullpublicViewTarget<ImageView,TranscodeType>into(@NonNullImageViewview){Util.assertMainThread();Preconditions.checkNotNull(view);BaseRequestOptions<?>requestOptions=this;if(!requestOptions.isTransformationSet()&&requestOptions.isTransformationAllowed()&&view.getScaleType()!=null){// Clone in this method so that if we use this RequestBuilder to load into a View and then// into a different target, we don't retain the transformation applied based on the previous// View's scale type.switch(view.getScaleType()){caseCENTER_CROP:requestOptions=requestOptions.clone().optionalCenterCrop();break;caseCENTER_INSIDE:requestOptions=requestOptions.clone().optionalCenterInside();break;caseFIT_CENTER:caseFIT_START:caseFIT_END:requestOptions=requestOptions.clone().optionalFitCenter();break;caseFIT_XY:requestOptions=requestOptions.clone().optionalCenterInside();break;caseCENTER:caseMATRIX:default:// Do nothing.}}returninto(//构建ImageViewTargetglideContext.buildImageViewTarget(view,transcodeClass),/*targetListener=*/null,requestOptions,Executors.mainThreadExecutor());}
private<YextendsTarget<TranscodeType>>Yinto(@NonNullYtarget,@NullableRequestListener<TranscodeType>targetListener,BaseRequestOptions<?>options,ExecutorcallbackExecutor){Preconditions.checkNotNull(target);if(!isModelSet){thrownewIllegalArgumentException("You must call #load() before calling #into()");}//构建RequestRequestrequest=buildRequest(target,targetListener,options,callbackExecutor);//获取前一个请求Requestprevious=target.getRequest();if(request.isEquivalentTo(previous)&&!isSkipMemoryCacheWithCompletePreviousRequest(options,previous)){// If the request is completed, beginning again will ensure the result is re-delivered,// triggering RequestListeners and Targets. If the request is failed, beginning again will// restart the request, giving it another chance to complete. If the request is already// running, we can let it continue running without interruption.if(!Preconditions.checkNotNull(previous).isRunning()){// Use the previous request rather than the new one to allow for optimizations like skipping// setting placeholders, tracking and un-tracking Targets, and obtaining View dimensions// that are done in the individual Request.previous.begin();}returntarget;}requestManager.clear(target);target.setRequest(request);//追踪RequestrequestManager.track(target,request);returntarget;}