美文网首页
Glide源码分析

Glide源码分析

作者: b42f47238b43 | 来源:发表于2019-06-16 20:38 被阅读0次

    Glide.whith(context).load(url).into(imageView);
    glide的使用方法很简单就上面面一行代码,但是却做着不简单的事。下面我们看一下Glide是怎么工作的

    whith()

      /**
       * @param context Any context, will not be retained.
       * @return A RequestManager for the top level application that can be used to start a load.
       * @see #with(android.app.Activity)
       * @see #with(android.app.Fragment)
       * @see #with(android.support.v4.app.Fragment)
       * @see #with(android.support.v4.app.FragmentActivity)
       */
      @NonNull
      public static RequestManager with(@NonNull Context context) {
        return getRetriever(context).get(context);
      }
    

    whith重载了很多方法我们分析其中一个就行了首先看看getRetriever方法做了什么

      @NonNull
      private static RequestManagerRetriever getRetriever(@Nullable Context context) {
    
        return Glide.get(context).getRequestManagerRetriever();
      }
    
     @NonNull
      public static Glide get(@NonNull Context context) {
        if (glide == null) {
          synchronized (Glide.class) {
            if (glide == null) {
              checkAndInitializeGlide(context);
            }
          }
        }
        return glide;
      }
    
      private static void checkAndInitializeGlide(@NonNull Context context) {
        initializeGlide(context);
      }
    
      private static void initializeGlide(@NonNull Context context) {
        initializeGlide(context, new GlideBuilder());
      }
    
      private static void initializeGlide(@NonNull Context context, @NonNull GlideBuilder builder) {
        Glide glide = builder.build(applicationContext);
        Glide.glide = glide;
      }
    
      @NonNull
      Glide build(@NonNull Context context) {
        //资源加载器
        if (sourceExecutor == null) {
          sourceExecutor = GlideExecutor.newSourceExecutor();
        }
        //磁盘缓存加载器
        if (diskCacheExecutor == null) {
          diskCacheExecutor = GlideExecutor.newDiskCacheExecutor();
        }
        //动画加载器
        if (animationExecutor == null) {
          animationExecutor = GlideExecutor.newAnimationExecutor();
        }
        //设置缓存大小
        if (memorySizeCalculator == null) {
          memorySizeCalculator = new MemorySizeCalculator.Builder(context).build();
        }
    
        if (connectivityMonitorFactory == null) {
          connectivityMonitorFactory = new DefaultConnectivityMonitorFactory();
        }
        //bitmap对象池
        if (bitmapPool == null) {
          int size = memorySizeCalculator.getBitmapPoolSize();
          if (size > 0) {
            bitmapPool = new LruBitmapPool(size);
          } else {
            bitmapPool = new BitmapPoolAdapter();
          }
        }
        //内存缓存
        if (arrayPool == null) {
          arrayPool = new LruArrayPool(memorySizeCalculator.getArrayPoolSizeInBytes());
        }
        if (memoryCache == null) {
          memoryCache = new LruResourceCache(memorySizeCalculator.getMemoryCacheSize());
        }
        //磁盘缓存
        if (diskCacheFactory == null) {
          diskCacheFactory = new InternalCacheDiskCacheFactory(context);
        }
        //图片加载引擎 核心
        if (engine == null) {
          engine =
              new Engine(
                  memoryCache,
                  diskCacheFactory,
                  diskCacheExecutor,
                  sourceExecutor,
                  GlideExecutor.newUnlimitedSourceExecutor(),
                  GlideExecutor.newAnimationExecutor(),
                  isActiveResourceRetentionAllowed);
        }
    
        if (defaultRequestListeners == null) {
          defaultRequestListeners = Collections.emptyList();
        } else {
          defaultRequestListeners = Collections.unmodifiableList(defaultRequestListeners);
        }
        //这个就是我们getRequestManagerRetriever方法返回的对象
        RequestManagerRetriever requestManagerRetriever =
            new RequestManagerRetriever(requestManagerFactory);
    
        return new Glide(
            context,
            engine,
            memoryCache,
            bitmapPool,
            arrayPool,
            requestManagerRetriever,
            connectivityMonitorFactory,
            logLevel,
            defaultRequestOptions.lock(),
            defaultTransitionOptions,
            defaultRequestListeners,
            isLoggingRequestOriginsEnabled);
      }
    

    以上代码可以看到getRetriever(context)方法会创建Glide对象并且返回一个RequestManagerRetriever对象,再看getRetriever(context).get(context)中get方法。

      @NonNull
      public RequestManager get(@NonNull 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);
      }
    
      @NonNull
      public RequestManager get(@NonNull FragmentActivity activity) {
      if (Util.isOnBackgroundThread()) {
          return get(activity.getApplicationContext());
        } else {
          assertNotDestroyed(activity);
          FragmentManager fm = activity.getSupportFragmentManager();
          return supportFragmentGet(
              activity, fm, /*parentHint=*/ null, isActivityVisible(activity));
        }
      }
    
      @NonNull
      private RequestManager supportFragmentGet(
          @NonNull Context context,
          @NonNull FragmentManager fm,
          @Nullable Fragment parentHint,
          boolean isParentVisible) {
        SupportRequestManagerFragment current =
            getSupportRequestManagerFragment(fm, parentHint, isParentVisible);
        RequestManager requestManager = current.getRequestManager();
        if (requestManager == null) {
          // TODO(b/27524013): Factor out this Glide.get() call.
          Glide glide = Glide.get(context);
          requestManager =
              factory.build(
                  glide, current.getGlideLifecycle(), current.getRequestManagerTreeNode(), context);
          current.setRequestManager(requestManager);
        }
        return requestManager;
      }
    
      @NonNull
      private RequestManager getApplicationManager(@NonNull Context context) {
              applicationManager =
                  factory.build(
                      glide,
                      new ApplicationLifecycle(),
                      new EmptyRequestManagerTreeNode(),
                      context.getApplicationContext());
        return applicationManager;
      }
    
    public class SupportRequestManagerFragment extends Fragment {
      public SupportRequestManagerFragment() {
        this(new ActivityFragmentLifecycle());
      }
    
      @VisibleForTesting
      @SuppressLint("ValidFragment")
      public SupportRequestManagerFragment(@NonNull ActivityFragmentLifecycle lifecycle) {
        this.lifecycle = 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();
        unregisterFragmentWithRoot();
      }
    }
    
    class ApplicationLifecycle implements Lifecycle {
      @Override
      public void addListener(@NonNull LifecycleListener listener) {
        listener.onStart();
      }
    
      @Override
      public void removeListener(@NonNull LifecycleListener listener) {
        // Do nothing.
      }
    }
    

    上面的流程get方法根据不同的Context对象进行分流如果当前线程是UI线程会创建一个SupportRequestManagerFragment添加到fragmentManager来绑定activity或者fragment的生命周期,如果当前线程是非UI线程则会绑定Application的生命周期。

    load()

    
      /**
       * Equivalent to calling {@link #asDrawable()} and then {@link RequestBuilder#load(String)}.
       *
       * @return A new request builder for loading a {@link Drawable} using the given model.
       */
      @NonNull
      @CheckResult
      @Override
      public RequestBuilder<Drawable> load(@Nullable String string) {
        //新建一个RequestBuild方法并调用load方法
        return asDrawable().load(string);
      }
    
      @NonNull
      @CheckResult
      public RequestBuilder<Drawable> asDrawable() {
        return as(Drawable.class);
      }
    
      @NonNull
      @CheckResult
      public <ResourceType> RequestBuilder<ResourceType> as(
          @NonNull Class<ResourceType> resourceClass) {
        return new RequestBuilder<>(glide, this, resourceClass, context);
      }
    
      @NonNull
      @Override
      @CheckResult
      public RequestBuilder<TranscodeType> load(@Nullable String string) {
        return loadGeneric(string);
      }
    
      @NonNull
      private RequestBuilder<TranscodeType> loadGeneric(@Nullable Object model) {
        this.model = model;
        isModelSet = true;
        return this;
      }
    

    这里就新建了一个RequestBuilder对象调用其load方法并保存了请求

    into()

     @NonNull
      public ViewTarget<ImageView, TranscodeType> into(@NonNull ImageView view) {
        ... ...
        return into(
            glideContext.buildImageViewTarget(view, transcodeClass),
            /*targetListener=*/ null,
            requestOptions,
            Executors.mainThreadExecutor());
      }
    

    这里调用了重载的into方法我们看一下glideContext.buildImageViewTarget(view, transcodeClass)方法

      @NonNull
      public <X> ViewTarget<ImageView, X> buildImageViewTarget(
          @NonNull ImageView imageView, @NonNull Class<X> transcodeClass) {
        return imageViewTargetFactory.buildTarget(imageView, transcodeClass);
      }
    
      @NonNull
      @SuppressWarnings("unchecked")
      public <Z> ViewTarget<ImageView, Z> buildTarget(@NonNull ImageView view,
          @NonNull Class<Z> clazz) {
        if (Bitmap.class.equals(clazz)) {
          return (ViewTarget<ImageView, Z>) new BitmapImageViewTarget(view);
        } else if (Drawable.class.isAssignableFrom(clazz)) {
          return (ViewTarget<ImageView, Z>) new DrawableImageViewTarget(view);
        } else {
          throw new IllegalArgumentException(
              "Unhandled class: " + clazz + ", try .as*(Class).transcode(ResourceTranscoder)");
        }
      }
    

    这里可以看出来传入的View被包了一层,在load方法的时候我们知道传进来的参数是Drawable.class所以返回一个DrawableImageViewTarget对象,再看into方法

     private <Y extends Target<TranscodeType>> Y into(
          @NonNull Y target,
          @Nullable RequestListener<TranscodeType> targetListener,
          BaseRequestOptions<?> options,
          Executor callbackExecutor) {
        Preconditions.checkNotNull(target);
        if (!isModelSet) {
          throw new IllegalArgumentException("You must call #load() before calling #into()");
        }
        //新建请求
        Request request = buildRequest(target, targetListener, options, callbackExecutor);
        //这个target就是刚刚新建的DrawableImageViewTarget对象
        //这里获取target保存的request
        Request previous = target.getRequest();
        if (request.isEquivalentTo(previous)
            && !isSkipMemoryCacheWithCompletePreviousRequest(options, previous)) {
          request.recycle();
          // 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();
          }
          return target;
        }
    
        requestManager.clear(target);
        //给target添加一个请求
        target.setRequest(request);
        //加载请求
        requestManager.track(target, request);
        return target;
      }
    
      private Request buildRequest(
          Target<TranscodeType> target,
          @Nullable RequestListener<TranscodeType> targetListener,
          BaseRequestOptions<?> requestOptions,
          Executor callbackExecutor) {
        return buildRequestRecursive(
            target,
            targetListener,
            /*parentCoordinator=*/ null,
            transitionOptions,
            requestOptions.getPriority(),
            requestOptions.getOverrideWidth(),
            requestOptions.getOverrideHeight(),
            requestOptions,
            callbackExecutor);
      }
    
      private Request buildRequestRecursive(
          Target<TranscodeType> target,
          @Nullable RequestListener<TranscodeType> targetListener,
          @Nullable RequestCoordinator parentCoordinator,
          TransitionOptions<?, ? super TranscodeType> transitionOptions,
          Priority priority,
          int overrideWidth,
          int overrideHeight,
          BaseRequestOptions<?> requestOptions,
          Executor callbackExecutor) {
    
        // Build the ErrorRequestCoordinator first if necessary so we can update parentCoordinator.
        ErrorRequestCoordinator errorRequestCoordinator = null;
        if (errorBuilder != null) {
          errorRequestCoordinator = new ErrorRequestCoordinator(parentCoordinator);
          parentCoordinator = errorRequestCoordinator;
        }
    
        Request mainRequest =
            buildThumbnailRequestRecursive(
                target,
                targetListener,
                parentCoordinator,
                transitionOptions,
                priority,
                overrideWidth,
                overrideHeight,
                requestOptions,
                callbackExecutor);
    
        if (errorRequestCoordinator == null) {
          return mainRequest;
        }
        ... ...
      }
    
    private Request buildThumbnailRequestRecursive(
          Target<TranscodeType> target,
          RequestListener<TranscodeType> targetListener,
          @Nullable RequestCoordinator parentCoordinator,
          TransitionOptions<?, ? super TranscodeType> transitionOptions,
          Priority priority,
          int overrideWidth,
          int overrideHeight,
          BaseRequestOptions<?> requestOptions,
          Executor callbackExecutor) {
        if (thumbnailBuilder != null) {
            ......
            //缩略图的处理
        } else {
          // Base case: no thumbnail.
          return obtainRequest(
              target,
              targetListener,
              requestOptions,
              parentCoordinator,
              transitionOptions,
              priority,
              overrideWidth,
              overrideHeight,
              callbackExecutor);
        }
      }
    
      private Request obtainRequest(
          Target<TranscodeType> target,
          RequestListener<TranscodeType> targetListener,
          BaseRequestOptions<?> requestOptions,
          RequestCoordinator requestCoordinator,
          TransitionOptions<?, ? super TranscodeType> transitionOptions,
          Priority priority,
          int overrideWidth,
          int overrideHeight,
          Executor callbackExecutor) {
        return SingleRequest.obtain(
            context,
            glideContext,
            model,
            transcodeClass,
            requestOptions,
            overrideWidth,
            overrideHeight,
            priority,
            target,
            targetListener,
            requestListeners,
            requestCoordinator,
            glideContext.getEngine(),
            transitionOptions.getTransitionFactory(),
            callbackExecutor);
      }
    

    最终我们新建的request是SingleRequest对象。我们再看一下requestManager.track(target, request);

      synchronized void track(@NonNull Target<?> target, @NonNull Request request) {
        //保存target到集合中
        targetTracker.track(target);
        requestTracker.runRequest(request);
      }
    
      public void runRequest(@NonNull Request request) {
        requests.add(request);
        if (!isPaused) {
          request.begin();
        } else {
          request.clear();
          if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "Paused, delaying request");
          }
          pendingRequests.add(request);
        }
      }
    

    因为我们request对象是SingleRequest所以我们看看SingleRequest的begin方法

      @Override
      public synchronized void begin() {
       ... ...
    
        if (status == Status.RUNNING) {
          throw new IllegalArgumentException("Cannot restart a running request");
        }
        //判断请求是否已经加载完成了 如果完成了直接加载到imageView中去
        if (status == Status.COMPLETE) {
          onResourceReady(resource, DataSource.MEMORY_CACHE);
          return;
        }
    
        // Restarts for requests that are neither complete nor running can be treated as new requests
        // and can run again from the beginning.
    
        status = Status.WAITING_FOR_SIZE;
        if (Util.isValidDimensions(overrideWidth, overrideHeight)) {
          //如果已经测量好了直接调用
          onSizeReady(overrideWidth, overrideHeight);
        } else {
          //测量size
          target.getSize(this);
        }
        ... ...
      }
    
     public void getSize(@NonNull SizeReadyCallback cb) {
        sizeDeterminer.getSize(cb);
      }
    
        void getSize(@NonNull SizeReadyCallback cb) {
          //确定宽高
          int currentWidth = getTargetWidth();
          int currentHeight = getTargetHeight();
          if (isViewStateAndSizeValid(currentWidth, currentHeight)) {
            //回调SingleRequest的onSizeReady方法。
            cb.onSizeReady(currentWidth, currentHeight);
            return;
          }
        }
    

    最终都会调用onSizeReady方法

    public synchronized void onSizeReady(int width, int height) {
        stateVerifier.throwIfRecycled();
        //标记当前请求为运行状态
        status = Status.RUNNING;
    
        loadStatus =
            engine.load(
                glideContext,
                model,
                requestOptions.getSignature(),
                this.width,
                this.height,
                requestOptions.getResourceClass(),
                transcodeClass,
                priority,
                requestOptions.getDiskCacheStrategy(),
                requestOptions.getTransformations(),
                requestOptions.isTransformationRequired(),
                requestOptions.isScaleOnlyOrNoTransform(),
                requestOptions.getOptions(),
                requestOptions.isMemoryCacheable(),
                requestOptions.getUseUnlimitedSourceGeneratorsPool(),
                requestOptions.getUseAnimationPool(),
                requestOptions.getOnlyRetrieveFromCache(),
                this,
                callbackExecutor);
      }
    
      public synchronized <R> LoadStatus load(
          GlideContext glideContext,
          Object model,
          Key signature,
          int width,
          int height,
          Class<?> resourceClass,
          Class<R> transcodeClass,
          Priority priority,
          DiskCacheStrategy diskCacheStrategy,
          Map<Class<?>, Transformation<?>> transformations,
          boolean isTransformationRequired,
          boolean isScaleOnlyOrNoTransform,
          Options options,
          boolean isMemoryCacheable,
          boolean useUnlimitedSourceExecutorPool,
          boolean useAnimationPool,
          boolean onlyRetrieveFromCache,
          ResourceCallback cb,
          Executor callbackExecutor) {
        long startTime = VERBOSE_IS_LOGGABLE ? LogTime.getLogTime() : 0;
        //根据一系列参数生成对应的key值
        EngineKey key = keyFactory.buildKey(model, signature, width, height, transformations,
            resourceClass, transcodeClass, options);
        
        //通过key值查看活动中的资源是否存在需要请求的资源如果存在则加载到imageView
        EngineResource<?> active = loadFromActiveResources(key, isMemoryCacheable);
        if (active != null) {
          cb.onResourceReady(active, DataSource.MEMORY_CACHE);
          if (VERBOSE_IS_LOGGABLE) {
            logWithTimeAndKey("Loaded resource from active resources", startTime, key);
          }
          return null;
        }
        //判断缓存中是否存在需要请求的资源如果有加载到imageVie
        EngineResource<?> cached = loadFromCache(key, isMemoryCacheable);
        if (cached != null) {
          cb.onResourceReady(cached, DataSource.MEMORY_CACHE);
          if (VERBOSE_IS_LOGGABLE) {
            logWithTimeAndKey("Loaded resource from cache", startTime, key);
          }
          return null;
        }
        //判断engineJob 是否存在  engineJob是一个工作执行器 
        EngineJob<?> current = jobs.get(key, onlyRetrieveFromCache);
        if (current != null) {
          //添加成功回调
          current.addCallback(cb, callbackExecutor);
          if (VERBOSE_IS_LOGGABLE) {
            logWithTimeAndKey("Added to existing load", startTime, key);
          }
          return new LoadStatus(cb, current);
        }
        //如果不存在新建engineJob
        EngineJob<R> engineJob =
            engineJobFactory.build(
                key,
                isMemoryCacheable,
                useUnlimitedSourceExecutorPool,
                useAnimationPool,
                onlyRetrieveFromCache);
        //新建DecodeJob对象该对象继承Runnable接口实现run方法加载请求
        DecodeJob<R> decodeJob =
            decodeJobFactory.build(
                glideContext,
                model,
                key,
                signature,
                width,
                height,
                resourceClass,
                transcodeClass,
                priority,
                diskCacheStrategy,
                transformations,
                isTransformationRequired,
                isScaleOnlyOrNoTransform,
                onlyRetrieveFromCache,
                options,
                engineJob);
        //缓存工作执行器
        jobs.put(key, engineJob);
        //添加回调
        engineJob.addCallback(cb, callbackExecutor);
        //启动工作线程
        engineJob.start(decodeJob);
    
        if (VERBOSE_IS_LOGGABLE) {
          logWithTimeAndKey("Started new load", startTime, key);
        }
        return new LoadStatus(cb, engineJob);
      }
    
     public synchronized void start(DecodeJob<R> decodeJob) {
        this.decodeJob = decodeJob;
        //开启线程池执行工作任务
        GlideExecutor executor = decodeJob.willDecodeFromCache()
            ? diskCacheExecutor
            : getActiveSourceExecutor();
        executor.execute(decodeJob);
      }
    
    public void run() {
          ... ...
          if (isCancelled) {
            notifyFailed();
            return;
          }
          runWrapped();
          ... ...
    }
    
      private void runWrapped() {
        switch (runReason) {
          //runReason的初始化实在DecodeJob的init方法中初始化的 默认是INITIALIZE
          case INITIALIZE:
            stage = getNextStage(Stage.INITIALIZE);
            currentGenerator = getNextGenerator();
            runGenerators();
            break;
          case SWITCH_TO_SOURCE_SERVICE:
            runGenerators();
            break;
          case DECODE_DATA:
            decodeFromRetrievedData();
            break;
          default:
            throw new IllegalStateException("Unrecognized run reason: " + runReason);
        }
      }
    
      private Stage getNextStage(Stage current) {
        switch (current) {
          //从磁盘缓存查找有没有缓存的图片
          case INITIALIZE:
            return diskCacheStrategy.decodeCachedResource()
                ? Stage.RESOURCE_CACHE : getNextStage(Stage.RESOURCE_CACHE);
          //从磁盘查找有没有缓存的原图
          case RESOURCE_CACHE:
            return diskCacheStrategy.decodeCachedData()
                ? Stage.DATA_CACHE : getNextStage(Stage.DATA_CACHE);
          //从网络查找
          case DATA_CACHE:
            // Skip loading from source if the user opted to only retrieve the resource from cache.
            return onlyRetrieveFromCache ? Stage.FINISHED : Stage.SOURCE;
          case SOURCE:
          case FINISHED:
            return Stage.FINISHED;
          default:
            throw new IllegalArgumentException("Unrecognized stage: " + current);
        }
      }
    
      private DataFetcherGenerator getNextGenerator() {
        switch (stage) {
          case RESOURCE_CACHE:
            return new ResourceCacheGenerator(decodeHelper, this);
          case DATA_CACHE:
            return new DataCacheGenerator(decodeHelper, this);
          case SOURCE:
            //从网络查找
            return new SourceGenerator(decodeHelper, this);
          case FINISHED:
            return null;
          default:
            throw new IllegalStateException("Unrecognized stage: " + stage);
        }
      }
    
     private void runGenerators() {
        currentThread = Thread.currentThread();
        startFetchTime = LogTime.getLogTime();
        boolean isStarted = false;
        //前面我们知道currentGenerator 是SourceGenerator所以我们看看他的startNext方法
        while (!isCancelled && currentGenerator != null
            && !(isStarted = currentGenerator.startNext())) {
          stage = getNextStage(stage);
          currentGenerator = getNextGenerator();
          ... ...
      }
    
      @Override
      public boolean startNext() {
        ...  ...
        boolean started = false;
        while (!started && hasNextModelLoader()) {
          loadData = helper.getLoadData().get(loadDataListIndex++);
          if (loadData != null
              && (helper.getDiskCacheStrategy().isDataCacheable(loadData.fetcher.getDataSource())
              || helper.hasLoadPath(loadData.fetcher.getDataClass()))) {
            started = true;
            //加载网络请求 Glide默认加载使用的是HttpUrlFetcher类
            loadData.fetcher.loadData(helper.getPriority(), this);
          }
        }
        return started;
      }
    
      @Override
      public void loadData(@NonNull Priority priority,
          @NonNull DataCallback<? super InputStream> callback) {
        long startTime = LogTime.getLogTime();
        try {
          InputStream result = loadDataWithRedirects(glideUrl.toURL(), 0, null, glideUrl.getHeaders());
          //获取输入流并回调SourceGenerator.onDataReady方法
          callback.onDataReady(result);
        } catch (IOException e) {
          if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "Failed to load data for url", e);
          }
          callback.onLoadFailed(e);
        } finally {
          if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "Finished http url fetcher fetch in " + LogTime.getElapsedMillis(startTime));
          }
        }
      }
    
     @Override
      public void onDataReady(Object data) {
           ... ...
          //cb是DecodeJob
          cb.onDataFetcherReady(loadData.sourceKey, data, loadData.fetcher,
              loadData.fetcher.getDataSource(), originalKey);
           ... ...
      }
    
      @Override
      public void onDataFetcherReady(Key sourceKey, Object data, DataFetcher<?> fetcher,
          DataSource dataSource, Key attemptedKey) {
            ... ...
            decodeFromRetrievedData();
            ... ...
        }
      }
    
      private void decodeFromRetrievedData() {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
          logWithTimeAndKey("Retrieved data", startFetchTime,
              "data: " + currentData
                  + ", cache key: " + currentSourceKey
                  + ", fetcher: " + currentFetcher);
        }
        Resource<R> resource = null;
        try {
          //将输入流转换为图片资源
          resource = decodeFromData(currentFetcher, currentData, currentDataSource);
        } catch (GlideException e) {
          e.setLoggingDetails(currentAttemptingKey, currentDataSource);
          throwables.add(e);
        }
        if (resource != null) {
          
          notifyEncodeAndRelease(resource, currentDataSource);
        } else {
          runGenerators();
        }
      }
    
      private void notifyEncodeAndRelease(Resource<R> resource, DataSource dataSource) {
        ........
        notifyComplete(result, dataSource);
        ........
      }
    
      private void notifyComplete(Resource<R> resource, DataSource dataSource) {
        setNotifiedOrThrow();
        callback.onResourceReady(resource, dataSource);
      }
    
     @Override
      public void onResourceReady(Resource<R> resource, DataSource dataSource) {
        this.resource = resource;
        this.dataSource = dataSource;
        //使用handle发送资源到主线程更新UI
        MAIN_THREAD_HANDLER.obtainMessage(MSG_COMPLETE, this).sendToTarget();
      }
    
     @Synthetic
      void handleResultOnMainThread() {
       ... ...
        for (ResourceCallback cb : cbs) {
          if (!isInIgnoredCallbacks(cb)) {
            engineResource.acquire();
            cb.onResourceReady(engineResource, dataSource);
          }
        }
      }
    
     public void onResourceReady(Resource<?> resource, DataSource dataSource) {
        ... ...
        onResourceReady((Resource<R>) resource, (R) received, dataSource);
      }
    
      private void onResourceReady(Resource<R> resource, R result, DataSource dataSource) {
         ... ...
        if (requestListener == null
            || !requestListener.onResourceReady(result, model, target, dataSource, isFirstResource)) {
          Transition<? super R> animation =
              animationFactory.build(dataSource, isFirstResource);
          target.onResourceReady(result, animation);
        }
      }
    
      @Override
      public void onResourceReady(Z resource, @Nullable Transition<? super Z> transition) {
        if (transition == null || !transition.transition(resource, this)) {
          setResourceInternal(resource);
        } else {
          maybeUpdateAnimatable(resource);
        }
      }
    
      private void setResourceInternal(@Nullable Z resource) {
        maybeUpdateAnimatable(resource);
        setResource(resource);
      }
      @Override
      protected void setResource(@Nullable Drawable resource) {
        view.setImageDrawable(resource);
      }
    

    整个glide的主体加载流程都已经过完了。

    相关文章

      网友评论

          本文标题:Glide源码分析

          本文链接:https://www.haomeiwen.com/subject/qetifctx.html