资讯专栏INFORMATION COLUMN

Glide源码分析

youkede / 1528人阅读

摘要:版本问题如何实现与生命周期的绑定如何实现缓存如何实现图片压缩如何实现与生命周期的绑定创建将其与传入的生命周期绑定这样做的好处是当时,也会做相应操作,如停掉图片加载绑定首先无论传入的是什么,只要是在子线程中调用创建的与绑定,这样创建的的生命周

版本4.9.0

问题

Glide如何实现与生命周期的绑定?

Glide如何实现缓存?

Glide如何实现图片压缩?

Glide如何实现与生命周期的绑定?

创建RequestManger,将其与with()传入 Activity, Fragment的生命周期绑定,
这样做的好处是当Activity/Fragment stop/destroy时,RequestManager也会做相应操作,如停掉图片加载

绑定Application Context

首先无论with()传入的是什么,只要是在子线程中调用,创建的RequestManger与 Application Context绑定,这样创建的RequestMangager的生命周期与

</>复制代码

  1. if (Util.isOnBackgroundThread()) {
  2. return get(fragment.getActivity().getApplicationContext());
  3. } else {
  4. ... ...
  5. }

这样做的目的是防止Activity,Fragment内存泄漏

Activity与FramgentActivity

</>复制代码

  1. class RequestManagerFragment {
  2. ... ...
  3. private final ActivityFragmentLifecycle lifecycle;
  4. @Override
  5. public void onStart() {
  6. super.onStart();
  7. lifecycle.onStart();
  8. }
  9. @Override
  10. public void onStop() {
  11. super.onStop();
  12. lifecycle.onStop();
  13. }
  14. @Override
  15. public void onDestroy() {
  16. super.onDestroy();
  17. lifecycle.onDestroy();
  18. unregisterFragmentWithRoot();
  19. }
  20. ... ...
  21. }

</>复制代码

  1. class ActivityFragmentLifecycle implements Lifecycle {
  2. @Override
  3. public void addListener(@NonNull LifecycleListener listener) {
  4. lifecycleListeners.add(listener);
  5. if (isDestroyed) {
  6. listener.onDestroy();
  7. } else if (isStarted) {
  8. listener.onStart();
  9. } else {
  10. listener.onStop();
  11. }
  12. }
  13. void onStart() {
  14. isStarted = true;
  15. for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
  16. lifecycleListener.onStart();
  17. }
  18. }
  19. void onStop() {
  20. isStarted = false;
  21. for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
  22. lifecycleListener.onStop();
  23. }
  24. }
  25. void onDestroy() {
  26. isDestroyed = true;
  27. for (LifecycleListener lifecycleListener : Util.getSnapshot(lifecycleListeners)) {
  28. lifecycleListener.onDestroy();
  29. }
  30. }
  31. }

</>复制代码

  1. RequestManagerFragment current = getRequestManagerFragment(fm,
  2. parentHint, isParentVisible);
  3. RequestManager requestManager = current.getRequestManager();
  4. if (requestManager == null) {
  5. // TODO(b/27524013): Factor out this Glide.get() call.
  6. Glide glide = Glide.get(context);
  7. requestManager = factory.build(glide, current.getGlideLifecycle(), current.getRequestManagerTreeNode(), context);
  8. current.setRequestManager(requestManager);
  9. }

RequestManagerFragment中创建了并对外提供ActivityFragmentLifecycle对象,
创建RequestManager时,传入ActivityFragmentLifecycle对象

</>复制代码

  1. RequestManager(
  2. Glide glide,
  3. Lifecycle lifecycle,
  4. RequestManagerTreeNode treeNode,
  5. RequestTracker requestTracker,
  6. ConnectivityMonitorFactory factory,
  7. Context context) {
  8. ... ...
  9. lifecycle.addListener(this);
  10. ... ...
  11. }
  12. @Override
  13. public synchronized void onStart() {
  14. resumeRequests();
  15. targetTracker.onStart();
  16. }
  17. @Override
  18. public synchronized void onStop() {
  19. pauseRequests();
  20. targetTracker.onStop();
  21. }
  22. @Override
  23. public synchronized void onDestroy() {
  24. targetTracker.onDestroy();
  25. for (Target target : targetTracker.getAll()) {
  26. clear(target);
  27. }
  28. targetTracker.clear();
  29. requestTracker.clearRequests();
  30. lifecycle.removeListener(this);
  31. lifecycle.removeListener(connectivityMonitor);
  32. mainHandler.removeCallbacks(addSelfToLifecycle);
  33. glide.unregisterRequestManager(this);
  34. }

这样RequestManger.onStart(),onStop(),onDestroy()与Activity的生命周期通过Activity绑定的空Fragment实现了绑定

Fragment
与Activity的绑定方式类似,

</>复制代码

  1. FragmentManager fm = fragment.getChildFragmentManager();

将RequestManger.onStart(),onStop(),onDestroy()与Fragment的生命周期通过Fragment绑定的空Fragment实现的绑定

View
通过View可以获取它所在的Activity 或 Fragment

</>复制代码

  1. Activity activity = findActivity(view.getContext());
  2. @Nullable
  3. private Activity findActivity(@NonNull Context context) {
  4. if (context instanceof Activity) {
  5. return (Activity) context;
  6. } else if (context instanceof ContextWrapper) {
  7. return findActivity(((ContextWrapper) context).getBaseContext());
  8. } else {
  9. return null;
  10. }
  11. }
  12. @Nullable
  13. private Fragment findSupportFragment(@NonNull View target, @NonNull
  14. FragmentActivity activity) {
  15. tempViewToSupportFragment.clear();
  16. findAllSupportFragmentsWithViews(
  17. activity.getSupportFragmentManager().getFragments(), tempViewToSupportFragment);
  18. Fragment result = null;
  19. View activityRoot = activity.findViewById(android.R.id.content);
  20. View current = target;
  21. while (!current.equals(activityRoot)) {
  22. result = tempViewToSupportFragment.get(current);
  23. if (result != null) {
  24. break;
  25. }
  26. if (current.getParent() instanceof View) {
  27. current = (View) current.getParent();
  28. } else {
  29. break;
  30. }
  31. }
  32. tempViewToSupportFragment.clear();
  33. return result;
  34. }

Context
通过Context获取Activity or FragmentActivity or Application Context

</>复制代码

  1. if (context == null) {
  2. throw new IllegalArgumentException("You cannot start a load on a nullContext");
  3. } else if (Util.isOnMainThread() && !(context instanceof Application)){
  4. if (context instanceof FragmentActivity) {
  5. return get((FragmentActivity) context);
  6. } else if (context instanceof Activity) {
  7. return get((Activity) context);
  8. } else if (context instanceof ContextWrapper) {
  9. return get(((ContextWrapper) context).getBaseContext());
  10. }
  11. }
  12. return getApplicationManager(context);

Glide如何实现缓存?

提供了两个内存缓存,分别存储强弱引用
弱引用的缓存: 存放正在使用的
强引用的缓存: 存放没有使用的

</>复制代码

  1. Map activeEngineResources//在
  2. private final Map cache = new LinkedHashMap<>(100, 0.75f, true);//在LruCache类中

查找内存缓存,

</>复制代码

  1. 1.先从弱引用的缓存查,
  2. 2.没有再从强引用的缓存查,查到后从强引用缓存中移除,加入到弱引用的缓存

Engine.load()方法

</>复制代码

  1. EngineResource active = loadFromActiveResources(key, isMemoryCacheable);
  2. if (active != null) {
  3. cb.onResourceReady(active, DataSource.MEMORY_CACHE);
  4. if (VERBOSE_IS_LOGGABLE) {
  5. logWithTimeAndKey("Loaded resource from active resources", startTime, key);
  6. }
  7. return null;
  8. }
  9. EngineResource cached = loadFromCache(key, isMemoryCacheable);

Engine.loadFromCache()方法

</>复制代码

  1. private EngineResource loadFromCache(Key key, boolean isMemoryCacheable) {
  2. if (!isMemoryCacheable) {
  3. return null;
  4. }
  5. EngineResource cached = getEngineResourceFromCache(key); //
  6. if (cached != null) {
  7. cached.acquire();
  8. activeResources.activate(key, cached);
  9. }
  10. return cached;
  11. }
  12. private EngineResource getEngineResourceFromCache(Key key) {
  13. Resource cached = cache.remove(key);
  14. final EngineResource result;
  15. if (cached == null) {
  16. result = null;
  17. } else if (cached instanceof EngineResource) {
  18. // Save an object allocation if we"ve cached an EngineResource (the typical case).
  19. result = (EngineResource) cached;
  20. } else {
  21. result = new EngineResource<>(cached, true /*isMemoryCacheable*/, true /*isRecyclable*/);
  22. }
  23. return result;
  24. }

Glide如何实现图片压缩?

Glide实现的等比压缩,保持原图长宽比例,主要是通过原图宽高和预设的宽高设置 BitmapFactory.Options.inSampleSize

</>复制代码

  1. float widthPercentage = requestedWidth / (float) sourceWidth;
  2. float heightPercentage = requestedHeight / (float) sourceHeight;
  3. exactScaleFactor = Math.min(widthPercentage, heightPercentage);
  4. int outWidth = round(exactScaleFactor * sourceWidth);
  5. int outHeight = round(exactScaleFactor * sourceHeight);
  6. int widthScaleFactor = sourceWidth / outWidth;
  7. int heightScaleFactor = sourceHeight / outHeight;
  8. int scaleFactor = rounding == SampleSizeRounding.MEMORY
  9. ? Math.max(widthScaleFactor, heightScaleFactor)
  10. : Math.min(widthScaleFactor, heightScaleFactor);
  11. int powerOfTwoSampleSize;
  12. // BitmapFactory does not support downsampling wbmp files on platforms <= M. See b/27305903.
  13. if (Build.VERSION.SDK_INT <= 23
  14. && NO_DOWNSAMPLE_PRE_N_MIME_TYPES.contains(options.outMimeType)) {
  15. powerOfTwoSampleSize = 1;
  16. } else {
  17. powerOfTwoSampleSize = Math.max(1, Integer.highestOneBit(scaleFactor));
  18. if (rounding == SampleSizeRounding.MEMORY
  19. && powerOfTwoSampleSize < (1.f / exactScaleFactor)) {
  20. powerOfTwoSampleSize = powerOfTwoSampleSize << 1;
  21. }
  22. }
  23. options.inSampleSize = powerOfTwoSampleSize;

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/73718.html

相关文章

  • Glide源码分析(一) Activity的生命周期与图片加载的关系

    摘要:从这段代码入手分析分析从这段代码可以看出无论传入的是还是或者干脆传入或都会调用这个方法而这个方法生成两个对象对象,并把它加到上对象这两个对象拥有共同的对象对象,当系统调用的生命周期,的生命周期随之被调用来处理列表,将的生命周期与的生命周期联 从这段代码入手分析Glide Glide.with(context) .load(url) .placehol...

    Kosmos 评论0 收藏0
  • Glide源码分析(三)

    Glide取消图片加载1.在任务刚开始时;2.在EngineJob中,Future.cancel(true)3.在加载完成,但没有加载到控件;RequestManager.java: public void pauseRequests() { Util.assertMainThread(); requestTracker.pauseRequests(); ...

    econi 评论0 收藏0

发表评论

0条评论

youkede

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<