您当前的位置: 首页 >  ide

lichong951

暂无认证

  • 2浏览

    0关注

    131博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Glide源码阅读之模板模式2

lichong951 发布时间:2022-01-29 10:13:26 ,浏览量:2

续接《Glide设计模式之模板模式1》

LifecycleListener已知的实现类列表如下:
  1. AppWidgetTarget
  2. BaseTarget
  3. BitmapImageViewTarget
  4. BitmapThumbnailImageViewTarget
  5. CustomTarget
  6. CustomViewTarget
  7. DrawableImageViewTarget
  8. DrawableThumbnailImageViewTarget
  9. ImageViewTarget
  10. NotificationTarget
  11. PreloadTarget
  12. RequestFutureTarget
  13. RequestManager
  14. SimpleTarget
  15. TargetTracker
  16. ThumbnailImageViewTarget
  17. ViewTarget
DrawableThumbnailImageViewTarget

com.bumptech.glide.request.target.DrawableThumbnailImageViewTarget 高效地显示多个连续加载到一个视图中的Drawables。


/**
 * Efficiently displays multiple Drawables loaded serially into a single {@link android.view.View}.
 */
 高效地显示多个连续加载到一个视图中的Drawables。
// Public API.
@SuppressWarnings("unused")
public class DrawableThumbnailImageViewTarget extends ThumbnailImageViewTarget {
  public DrawableThumbnailImageViewTarget(ImageView view) {
    super(view);
  }

  /** @deprecated Use {@link #waitForLayout()} instead. */
  @Deprecated
  @SuppressWarnings("deprecation")
  public DrawableThumbnailImageViewTarget(ImageView view, boolean waitForLayout) {
    super(view, waitForLayout);
  }

  @Override
  protected Drawable getDrawable(Drawable resource) {
    return resource;
  }
}

NotificationTarget

com.bumptech.glide.request.target.NotificationTarget 这个类用于通过RemoteViews在一个通知的ImageView中显示下载的位图。 注意:为了使取消正常工作,您必须在每次后续加载时传入这个类的相同实例。

/**
 * This class is used to display downloaded Bitmap inside an ImageView of a Notification through
 * RemoteViews.
 *
 * 

Note - For cancellation to work correctly, you must pass in the same instance of this class * for every subsequent load. */ 这个类用于通过RemoteViews在一个通知的ImageView中显示下载的位图。 注意:为了使取消正常工作,您必须在每次后续加载时传入这个类的相同实例。 // Public API. @SuppressWarnings({"WeakerAccess", "unused"}) public class NotificationTarget extends CustomTarget {

PreloadTarget

com.bumptech.glide.request.target.PreloadTarget 一次性使用的Target类,它将资源加载到内存中,然后清除自己。


/**
 * A one time use {@link com.bumptech.glide.request.target.Target} class that loads a resource into
 * memory and then clears itself.
 *
 * @param  The type of resource that will be loaded into memory.
 */
 一次性使用的Target类,它将资源加载到内存中,然后清除自己
public final class PreloadTarget extends CustomTarget {
  private static final int MESSAGE_CLEAR = 1;
  private static final Handler HANDLER =
      new Handler(
          Looper.getMainLooper(),
          new Callback() {
            @Override
            public boolean handleMessage(Message message) {
              if (message.what == MESSAGE_CLEAR) {
                ((PreloadTarget) message.obj).clear();
                return true;
              }
              return false;
            }
          });

  private final RequestManager requestManager;

  /**
   * Returns a PreloadTarget.
   *
   * @param width The width in pixels of the desired resource.
   * @param height The height in pixels of the desired resource.
   * @param  The type of the desired resource.
   */
  public static  PreloadTarget obtain(RequestManager requestManager, int width, int height) {
    return new PreloadTarget(requestManager, width, height);
  }

  private PreloadTarget(RequestManager requestManager, int width, int height) {
    super(width, height);
    this.requestManager = requestManager;
  }

  @Override
  public void onResourceReady(@NonNull Z resource, @Nullable Transition transition) {
    // If a thumbnail request is set and the thumbnail completes, we don't want to cancel the
    // primary load. Instead we wait until the primary request (the one set on the target) says
    // that it is complete.
    // Note - Any thumbnail request that does not complete before the primary request will be
    // cancelled and may not be preloaded successfully. Cancellation of outstanding thumbnails after
    // the primary request succeeds is a common behavior of all Glide requests and we're not trying
    // to override it here.
    Request request = getRequest();
    if (request != null && request.isComplete()) {
      HANDLER.obtainMessage(MESSAGE_CLEAR, this).sendToTarget();
    }
  }

  @Override
  public void onLoadCleared(@Nullable Drawable placeholder) {
    // Do nothing, we don't retain a reference to our resource.
  }

  @SuppressWarnings("WeakerAccess")
  @Synthetic
  void clear() {
    requestManager.clear(this);
  }
}

RequestFutureTarget

com.bumptech.glide.request.RequestFutureTarget 一个未来的Glide实现,可用于在后台线程以阻塞方式加载资源

/**
 * A {@link java.util.concurrent.Future} implementation for Glide that can be used to load resources
 * in a blocking manner on background threads.
 *
 * 

Note - Unlike most targets, RequestFutureTargets can be used once and only once. Attempting to * reuse a RequestFutureTarget will probably result in undesirable behavior or exceptions. Instead * of reusing objects of this class, the pattern should be: * *

{@code
 * FutureTarget target = null;
 * RequestManager requestManager = Glide.with(context);
 * try {
 *   target = requestManager
 *      .downloadOnly()
 *      .load(model)
 *      .submit();
 *   File downloadedFile = target.get();
 *   // ... do something with the file (usually throws IOException)
 * } catch (ExecutionException | InterruptedException | IOException e) {
 *   // ... bug reporting or recovery
 * } finally {
 *   // make sure to cancel pending operations and free resources
 *   if (target != null) {
 *     target.cancel(true); // mayInterruptIfRunning
 *   }
 * }
 * }
* * The {@link #cancel(boolean)} call will cancel pending operations and make sure that any resources * used are recycled. * * @param The type of the resource that will be loaded. */ 一个未来的Glide实现,可用于在后台线程以阻塞方式加载资源。 注意:与大多数目标不同,RequestFutureTargets只能被使用一次。试图重用RequestFutureTarget可能会导致不良的行为或异常。与其重用这个类的对象,模式应该是: FutureTarget目标= null; RequestManager RequestManager = Glide.with(context); 尝试{ 目标= requestManager .downloadOnly () .load(模型) 。submit (); filedownloaddfile = target.get(); / /……对文件做一些事情(通常抛出IOException) } catch (ExecutionException | InterruptedException | IOException e) { / /……Bug报告或修复 最后}{ //确保取消挂起的操作和释放资源 If (target != null) { target.cancel(真正的);/ / mayInterruptIfRunning } } cancel(boolean)调用将取消挂起的操作,并确保所有使用的资源都被回收。 public class RequestFutureTarget implements FutureTarget, RequestListener {
FutureTarget

com.bumptech.glide.request.FutureTarget 既是目标又是未来的对象的接口


/**
 * An interface for an object that is both a {@link com.bumptech.glide.request.target.Target} and a
 * {@link java.util.concurrent.Future}. For example:
 *
 * 
{@code
 * FutureTarget futureTarget = Glide.with(fragment)
 *                                       .load("http://goo.gl/1asf12")
 *                                       .asBitmap()
 *                                       .into(250, 250);
 * Bitmap myBitmap = futureTarget.get();
 * ... // do things with bitmap and then release when finished:
 * futureTarget.cancel(false);
 * }
* *

Note - {@link #get()} and {@link #get(long, java.util.concurrent.TimeUnit)} must be called off * of the main thread or they will block forever. * * @param The type of resource this FutureTarget will retrieve. */ 既是目标又是未来的对象的接口。例如: FutureTarget FutureTarget = Glide.with(fragment) .load(“http://goo.gl/1asf12”) .asBitmap () .into(250、250); Bitmap myBitmap = futureTarget.get(); ... //使用bitmap做事情,然后在完成时释放: futureTarget.cancel(假); 注意- Future.get()和Future。get(long, java.util.concurrent.TimeUnit)必须从主线程中调用,否则它们将永远阻塞。 public interface FutureTarget extends Future, Target {}

RequestManager

com.bumptech.glide.RequestManager 用于管理和启动Glide请求的类。可以使用活动、片段和连接生命周期事件来智能地停止、启动和重新启动请求。通过实例化一个新对象来检索,或者利用内置的Activity和Fragment生命周期处理,使用静态Glide。用Fragment或Activity加载方法。


/**
 * A class for managing and starting requests for Glide. Can use activity, fragment and connectivity
 * lifecycle events to intelligently stop, start, and restart requests. Retrieve either by
 * instantiating a new object, or to take advantage built in Activity and Fragment lifecycle
 * handling, use the static Glide.load methods with your Fragment or Activity.
 *
 * @see Glide#with(android.app.Activity)
 * @see Glide#with(androidx.fragment.app.FragmentActivity)
 * @see Glide#with(android.app.Fragment)
 * @see Glide#with(androidx.fragment.app.Fragment)
 * @see Glide#with(Context)
 */
 用于管理和启动Glide请求的类。可以使用活动、片段和连接生命周期事件来智能地停止、启动和重新启动请求。通过实例化一个新对象来检索,或者利用内置的Activity和Fragment生命周期处理,使用静态Glide。用Fragment或Activity加载方法。
public class RequestManager
    implements ComponentCallbacks2, LifecycleListener, ModelTypes {
  private static final RequestOptions DECODE_TYPE_BITMAP = decodeTypeOf(Bitmap.class).lock();
  private static final RequestOptions DECODE_TYPE_GIF = decodeTypeOf(GifDrawable.class).lock();
  private static final RequestOptions DOWNLOAD_ONLY_OPTIONS =
      diskCacheStrategyOf(DiskCacheStrategy.DATA).priority(Priority.LOW).skipMemoryCache(true);

  protected final Glide glide;
  protected final Context context;

  @SuppressWarnings("WeakerAccess")
  @Synthetic
  final Lifecycle lifecycle;
   @GuardedBy("this")
  private final RequestTracker requestTracker;

  @GuardedBy("this")
  private final RequestManagerTreeNode treeNode;

  @GuardedBy("this")
  private final TargetTracker targetTracker = new TargetTracker();

 private final Runnable addSelfToLifecycle =
      new Runnable() {
        @Override
        public void run() {
          lifecycle.addListener(RequestManager.this);
        }
      };


  /**
   * 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 synchronized void onStart() {
    resumeRequests();
    targetTracker.onStart();
  }

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

  /**
   * Lifecycle callback that cancels all in progress requests and clears and recycles resources for
   * all completed requests.
   */
  @Override
  public synchronized void onDestroy() {
    targetTracker.onDestroy();
    for (Target target : targetTracker.getAll()) {
      clear(target);
    }
    targetTracker.clear();
    requestTracker.clearRequests();
    lifecycle.removeListener(this);
    lifecycle.removeListener(connectivityMonitor);
    Util.removeCallbacksOnUiThread(addSelfToLifecycle);
    glide.unregisterRequestManager(this);
  }


RequestManager是一个比较复杂的类。涉及的业务逻辑比较多,本文只关注从接口和抽象类集成过了后实现的部分,专注模板模式的业务实现。便于理解

SimpleTarget

com.bumptech.glide.request.target.SimpleTarget 一个简单的Target基类,具有非基本方法的默认(通常为no-op)实现,允许调用者指定确切的宽度/高度。 已弃用


/**
 * A simple {@link com.bumptech.glide.request.target.Target} base class with default (usually no-op)
 * implementations of non essential methods that allows the caller to specify an exact width/height.
 * Typically use cases look something like this:
 *
 * 
 * 
 * Target target =
 *     Glide.with(fragment)
 *       .asBitmap()
 *       .load("http://somefakeurl.com/fakeImage.jpeg")
 *       .apply(fitCenterTransform())
 *       .into(new SimpleTarget(250, 250) {
 *
 *         {@literal @Override}
 *         public void onResourceReady(Bitmap resource, Transition            
关注
打赏
1659512212
查看更多评论
0.0757s