从Glide入口开始 Glide最简单的用法如下所示
1 2 3 4 5 6 7 8 Glide.with(context); .load(url) .diskCacheStrategy(DiskCacheStrategy.ALL) .skipMemoryCache(false ) .centerCrop() .into(imageView);
with(context) 1 2 3 4 public static RequestManager with (Context context) { RequestManagerRetriever retriever = RequestManagerRetriever.get(); return retriever.get(context); }
RequestManagerRetriever get(context) 依据传入的context的类型, 进行相应的操作. context的类型主要分为FragmentActivity, Activity和ContextWrapper, 当context是ContextWrapper时, 调用get(Context context)查看其封装的是哪一种Activity.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 RequestManagerRetriever.java 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) { 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(Activity) get(FragmentActivity) 1 2 3 4 5 6 7 8 9 10 11 RequestManagerRetriever.java public RequestManager get (FragmentActivity activity) { if (Util.isOnBackgroundThread()) { return get(activity.getApplicationContext()); } else { assertNotDestroyed(activity); FragmentManager fm = activity.getSupportFragmentManager(); return supportFragmentGet(activity, fm); } }
1 2 3 4 5 6 7 8 9 10 11 12 @TargetApi (Build.VERSION_CODES.HONEYCOMB)public RequestManager get (Activity activity) { if (Util.isOnBackgroundThread() || Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { return get(activity.getApplicationContext()); } else { assertNotDestroyed(activity); android.app.FragmentManager fm = activity.getFragmentManager(); return fragmentGet(activity, fm); } }
这两个方法差别不大, 主要是因为FragmentActivity来自于support v4库中, 和标准库Activity获取FragmentManager的方法以及返回的FragmentManager类型不太相同.
RequestManagerRetriever fragmentGet(Context, FramentManager) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 RequestManagerRetriever.java @TargetApi (Build.VERSION_CODES.JELLY_BEAN_MR1)RequestManagerFragment getRequestManagerFragment (final android.app.FragmentManager fm) { RequestManagerFragment current = (RequestManagerFragment) fm.findFragmentByTag(FRAGMENT_TAG); if (current == null ) { current = pendingRequestManagerFragments.get(fm); if (current == null ) { current = new RequestManagerFragment(); pendingRequestManagerFragments.put(fm, current); fm.beginTransaction().add(current, FRAGMENT_TAG).commitAllowingStateLoss(); handler.obtainMessage(ID_REMOVE_FRAGMENT_MANAGER, fm).sendToTarget(); } } return current; } @TargetApi (Build.VERSION_CODES.HONEYCOMB)RequestManager fragmentGet (Context context, android.app.FragmentManager fm) { RequestManagerFragment current = getRequestManagerFragment(fm); RequestManager requestManager = current.getRequestManager(); if (requestManager == null ) { requestManager = new RequestManager(context, current.getLifecycle(), current.getRequestManagerTreeNode()); current.setRequestManager(requestManager); } return requestManager; }
这两段代码的主要意义在于生成一个RequestManagerFragment并没有内容的但是绑定在制定的context上. 其实目的就是将该Fragment的生命周期绑定在该context上, 并在相应的方法调用时执行相应的操作.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 RequestManagerFragment.java ActivityFragmentLifecycle lifecycle; @Override public void onStart () { super .onStart(); lifecycle.onStart(); } @Override public void onStop () { super .onStop(); lifecycle.onStop(); } @Override public void onDestroy () { super .onDestroy(); lifecycle.onDestroy(); }
RequestManager 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 RequestManager implements LifecycleListener @Override public void onStart () { resumeRequests(); } @Override public void onStop () { pauseRequests(); } @Override public void onDestroy () { requestTracker.clearRequests(); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 class ActivityFragmentLifecycle implements Lifecycle { private final Set<LifecycleListener> lifecycleListeners = Collections.newSetFromMap(new WeakHashMap<LifecycleListener, Boolean>()); private boolean isStarted; private boolean isDestroyed; @Override public void addListener (LifecycleListener listener) { lifecycleListeners.add(listener); if (isDestroyed) { listener.onDestroy(); } else if (isStarted) { listener.onStart(); } else { listener.onStop(); } } void onStart () { isStarted = true ; for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) { lifecycleListener.onStart(); } } void onStop () { isStarted = false ; for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) { lifecycleListener.onStop(); } } void onDestroy () { isDestroyed = true ; for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) { lifecycleListener.onDestroy(); } } }
上述的代码总体的目的就是将RequestManager的生命周期和RequestManagerFragment绑定起来, 进而和Activity的生命周期绑定起来.
RequestManager 下面来看一下RequestManager的功能.
构造函数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 RequestManager.java public RequestManager (Context context, Lifecycle lifecycle, RequestManagerTreeNode treeNode) { this (context, lifecycle, treeNode, new RequestTracker(), new ConnectivityMonitorFactory()); } RequestManager(Context context, final Lifecycle lifecycle, RequestManagerTreeNode treeNode, RequestTracker requestTracker, ConnectivityMonitorFactory factory) { this .context = context.getApplicationContext(); this .lifecycle = lifecycle; this .treeNode = treeNode; this .requestTracker = requestTracker; this .glide = Glide.get(context); this .optionsApplier = new OptionsApplier(); ConnectivityMonitor connectivityMonitor = factory.build(context, new RequestManagerConnectivityListener(requestTracker)); if (Util.isOnBackgroundThread()) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run () { lifecycle.addListener(RequestManager.this ); } }); } else { lifecycle.addListener(this ); } lifecycle.addListener(connectivityMonitor); }
Glide.get(context) 该方法就是利用单例模式获取一个Glide实例.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Glide.java private static volatile Glide glide;public static Glide get (Context context) { if (glide == null ) { synchronized (Glide.class) { if (glide == null ) { Context applicationContext = context.getApplicationContext(); List<GlideModule> modules = new ManifestParser(applicationContext).parse(); GlideBuilder builder = new GlideBuilder(applicationContext); for (GlideModule module : modules) { module .applyOptions(applicationContext, builder); } glide = builder.createGlide(); for (GlideModule module : modules) { module .registerComponents(applicationContext, glide); } } } } return glide; }
GlideBuilder 利用GlideBuilder中的createGlide()方法生成了Glide, 在这个过程中完成了以下几个任务:
初始化线程池
初始化bitmap池
初始化内存缓存类
初始化内部磁盘缓存类
初始化引擎类
设置默认的解码格式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 GlideBuilder.java Glide createGlide () { if (sourceService == null ) { final int cores = Math.max(1 , Runtime.getRuntime().availableProcessors()); sourceService = new FifoPriorityThreadPoolExecutor(cores); } if (diskCacheService == null ) { diskCacheService = new FifoPriorityThreadPoolExecutor(1 ); } MemorySizeCalculator calculator = new MemorySizeCalculator(context); if (bitmapPool == null ) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { int size = calculator.getBitmapPoolSize(); bitmapPool = new LruBitmapPool(size); } else { bitmapPool = new BitmapPoolAdapter(); } } if (memoryCache == null ) { memoryCache = new LruResourceCache(calculator.getMemoryCacheSize()); } if (diskCacheFactory == null ) { diskCacheFactory = new InternalCacheDiskCacheFactory(context); } if (engine == null ) { engine = new Engine(memoryCache, diskCacheFactory, diskCacheService, sourceService); } if (decodeFormat == null ) { decodeFormat = DecodeFormat.DEFAULT; } return new Glide(engine, memoryCache, bitmapPool, context, decodeFormat); }
ManifestParser 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 ManifestParser.java private static final String GLIDE_MODULE_VALUE = "GlideModule" ;public List<GlideModule> parse () { List<GlideModule> modules = new ArrayList<GlideModule>(); try { ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo( context.getPackageName(), PackageManager.GET_META_DATA); if (appInfo.metaData != null ) { for (String key : appInfo.metaData.keySet()) { if (GLIDE_MODULE_VALUE.equals(appInfo.metaData.get(key))) { modules.add(parseModule(key)); } } } } catch (PackageManager.NameNotFoundException e) { throw new RuntimeException("Unable to find metadata to parse GlideModules" , e); } return modules; } private static GlideModule parseModule (String className) { Class<?> clazz; try { clazz = Class.forName(className); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Unable to find GlideModule implementation" , e); } Object module ; try { module = clazz.newInstance(); } catch (InstantiationException e) { throw new RuntimeException("Unable to instantiate GlideModule implementation for " + clazz, e); } catch (IllegalAccessException e) { throw new RuntimeException("Unable to instantiate GlideModule implementation for " + clazz, e); } if (!(module instanceof GlideModule)) { throw new RuntimeException("Expected instanceof GlideModule, but found: " + module ); } return (GlideModule) module ; }
通过反射的方式获取在Manifest.xml中自定义的GlideModule对象, 获得之后遍历ArrayList, 对每一个GlideModuled调用相应的applyOptions()和registerComponents()方法.