主頁 > 前端設計 > Glide你需要知道的事(原始碼決議)

Glide你需要知道的事(原始碼決議)

2020-10-21 23:44:23 前端設計

目錄

前言:

Picasso、Fresco、Glide:

Picasso與Glide對比

Fresco與Glide對比

小結

Glide原理決議

1.快取原理

小結1

2.生命周期處理

小結2

總結


前言:

專案中經常用到Glide、面試也有被問到,是時候系統的深入了解一下Glide了,


Picasso、Fresco、Glide:

做Android開發的,對上述圖片加載框架,應該比較熟悉了,我簡單的介紹一下,對比分析一下,

Picasso是Square公司開源的專案,功能強大、呼叫簡單:

Picasso
    .with(context)
    .load(Url)
    .into(targetImageView);

Glide是谷歌員工開源的一個專案,呼叫方式如下:

Glide
    .with(context)
    .load(Url)
    .into(targetImageView);

Picasso與Glide對比

從上面可以看出,二者的呼叫方式幾乎相同,有著近乎一樣的API風格,但Glide在快取策略和加載GIF方面略勝一籌,主要區別如下:

1.呼叫方式上:Glide with接收的引數不僅僅是context,還可以是Activity、Fragment,并且和Activity、Fragment生命周期保持一致,在Pasuse,暫停加載圖片,Resume的時候,恢復加載(后面重點介紹),

2.磁盤快取和圖片格式:Picasso使用的是全尺寸快取,Glide和使用的ImageView大小相同,相比來說,Glide加載圖片較Picasso要快,Picasso加載前需要重新調整大小,Picasso默認使用的圖片格式是ARGB8888,Glide默認使用的圖片格式是RGB565,后者要比前者相同情況下,少一半記憶體,

3.支持GIF:Glide支持加載GIF動圖、Picasso不支持,

4.包大小:Glide要比Picasso大一些,

Fresco是Facebook開源的圖片庫,和Glide具備相同的功能(支持加載gif),

Fresco與Glide對比

Fresco最大的亮點在于它的記憶體管理,Android 解壓后的圖片即Android中的Bitmap,占用大量的記憶體,Android 5.0以下系統,會顯著的引發界面卡頓,Freco很好的解決了這個問題,Fresco和Glide主要區別如下:

1.Glide加載速度快(快取的圖片規格多),記憶體開銷小(rgb565),

2.Fresco最大的優勢在于5.0(Android 2.3)以下bitmap的加載,5.0以下系統,Fresco將圖片放在一個特別的記憶體區域,大大減少OOM,

3.Fresco包比較大,使用麻煩,適合高性能加載大量圖片,

小結

1.Picasso所能實作的功能,Glide都能實作,只是設定不同,二者區別是Picasso包體積比Glide小且圖片質量比Glide高,但Glide加載速度比Picasso快,Glide支持gif,適合處理大型圖片流,如果視頻類應用,首選Glide,

2.Fresco綜合之前圖片加載庫的優點,在5.0以下記憶體優化比較好,但包體積比較大,Fresco>Glide>Picasso,Fresco在圖片較多的應用凸顯其價值,但如果應用對圖片需求較少的,不推薦使用,


Glide原理決議

這里我只分析Glide的快取原理和生命周期處理,不知道大家怎么學習的,在使用了大量的框架的時候,我發現要學習一個東西,大概一個步驟就是,這個東西是什么,用來干什么,使用、熟練使用,了解原理,最后融會貫通,其實分析原始碼的程序,最簡單的就是從呼叫方式出發,一步一步往下看,基本就能了解個大概,剛開始看的時候,有點吃力,多看幾遍就ok了,話不多說,接下來分兩個部分介紹:

1.快取原理

2.生命周期處理

以下原始碼基于:glide:4.6.1

溫馨提示:原理代碼分析程序較長,如果不想看的話,可直接跳轉到小結1、小結2,

1.快取原理

在前面Glide和Picasso對比介紹的時候,我們已經描述了Glide最基本呼叫程序:

Glide
    .with(context)
    .load(Url)
    .into(targetImageView);

從上述代碼可以看出,with傳人的是context背景關系,load加載圖片資源resouce,into是設定到具體的Imageview處理顯示,根據以往經驗,into應該是加載圖片的起點,我們先看里面的原始碼,

點進去發現有幾個構造多載方法,隨便點擊去一個,我們會發現最終呼叫的方法是下面這個方法:

  private <Y extends Target<TranscodeType>> Y into(
      @NonNull Y target,
      @Nullable RequestListener<TranscodeType> targetListener,
      @NonNull RequestOptions options) {
    // 是否在主執行緒
    Util.assertMainThread();
   // 判斷加載圖片target是否為空
    Preconditions.checkNotNull(target);
   // 沒有設定圖片資源報錯
    if (!isModelSet) {
      throw new IllegalArgumentException("You must call #load() before calling #into()");
    }
    // 圖片資源格式clone
    options = options.autoClone();
    // 構造圖片請求request
    Request request = buildRequest(target, targetListener, options);
    // 獲取當前request
    Request previous = target.getRequest();
    // 新創建的request和當前相同,將新構造的request回收并復用當前request
    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.
      // 如果當前request正在運行,直接開始加載圖片
      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;
    }
    // 清除當前request
    requestManager.clear(target);
    // 將新構造的請求和當前target系結起來
    target.setRequest(request);
    // 開始處理新構造的request
    requestManager.track(target, request);

    return target;
  }

從上面的原始碼可以看出,當我們into加載圖片首先會構造一個新的圖片request,我們看下buildRequest(target, targetListener, options)這個方法做了那些處理,我們跟進去會發現,最終呼叫的是buildRequestRecursive()方法,

  private Request buildRequestRecursive(
      Target<TranscodeType> target,
      @Nullable RequestListener<TranscodeType> targetListener,
      @Nullable RequestCoordinator parentCoordinator,
      TransitionOptions<?, ? super TranscodeType> transitionOptions,
      Priority priority,
      int overrideWidth,
      int overrideHeight,
      RequestOptions requestOptions) {

    // Build the ErrorRequestCoordinator first if necessary so we can update parentCoordinator.
    // 創建一個錯誤處理器,以便后面可以更新原來的parentCoordinator
    ErrorRequestCoordinator errorRequestCoordinator = null;
    if (errorBuilder != null) {
      errorRequestCoordinator = new ErrorRequestCoordinator(parentCoordinator);
      parentCoordinator = errorRequestCoordinator;
    }
    // 構造一個mainRequest
    Request mainRequest =
        buildThumbnailRequestRecursive(
            target,
            targetListener,
            parentCoordinator,
            transitionOptions,
            priority,
            overrideWidth,
            overrideHeight,
            requestOptions);
    // 之前傳入的parentCoordinator == null 直接回傳構造的request
    if (errorRequestCoordinator == null) {
      return mainRequest;
    }
    
    // 為errorRequest圖片寬、高賦值,為后續請求準備
    int errorOverrideWidth = errorBuilder.requestOptions.getOverrideWidth();
    int errorOverrideHeight = errorBuilder.requestOptions.getOverrideHeight();
    if (Util.isValidDimensions(overrideWidth, overrideHeight)
        && !errorBuilder.requestOptions.isValidOverride()) {
      errorOverrideWidth = requestOptions.getOverrideWidth();
      errorOverrideHeight = requestOptions.getOverrideHeight();
    }
    // 構造一個errorRequest,并回傳
    Request errorRequest = errorBuilder.buildRequestRecursive(
        target,
        targetListener,
        errorRequestCoordinator,
        errorBuilder.transitionOptions,
        errorBuilder.requestOptions.getPriority(),
        errorOverrideWidth,
        errorOverrideHeight,
        errorBuilder.requestOptions);
    errorRequestCoordinator.setRequests(mainRequest, errorRequest);
    return errorRequestCoordinator;
  }

從上面代碼可以看出,他首先會創建一個ErrorRequestCoordinator調度器,來更新之前傳入的parentCoordinator,之前傳入的代碼如下:

return buildRequestRecursive(
        target,
        targetListener,
        /*parentCoordinator=*/ null,
        transitionOptions,
        requestOptions.getPriority(),
        requestOptions.getOverrideWidth(),
        requestOptions.getOverrideHeight(),
        requestOptions);

可以看出直接傳入了一個null,所以errorRequestCoordinator = null,直接回傳mainRequest;我們再一下mainRequest如何創建的:

  private Request buildThumbnailRequestRecursive(
      Target<TranscodeType> target,
      RequestListener<TranscodeType> targetListener,
      @Nullable RequestCoordinator parentCoordinator,
      TransitionOptions<?, ? super TranscodeType> transitionOptions,
      Priority priority,
      int overrideWidth,
      int overrideHeight,
      RequestOptions requestOptions) {
    if (thumbnailBuilder != null) {
      // Recursive case: contains a potentially recursive thumbnail request builder.
      ...

      ThumbnailRequestCoordinator coordinator = new ThumbnailRequestCoordinator(parentCoordinator);
      Request fullRequest =
          obtainRequest(
              target,
              targetListener,
              requestOptions,
              coordinator,
              transitionOptions,
              priority,
              overrideWidth,
              overrideHeight);
      isThumbnailBuilt = true;
      // Recursively generate thumbnail requests.
      Request thumbRequest =
          thumbnailBuilder.buildRequestRecursive(
              target,
              targetListener,
              coordinator,
              thumbTransitionOptions,
              thumbPriority,
              thumbOverrideWidth,
              thumbOverrideHeight,
              thumbnailBuilder.requestOptions);
      isThumbnailBuilt = false;
      coordinator.setRequests(fullRequest, thumbRequest);
      return coordinator;
    } else if (thumbSizeMultiplier != null) {
      // Base case: thumbnail multiplier generates a thumbnail request, but cannot recurse.
      ThumbnailRequestCoordinator coordinator = new ThumbnailRequestCoordinator(parentCoordinator);
      Request fullRequest =
          obtainRequest(
              target,
              targetListener,
              requestOptions,
              coordinator,
              transitionOptions,
              priority,
              overrideWidth,
              overrideHeight);
      RequestOptions thumbnailOptions = requestOptions.clone()
          .sizeMultiplier(thumbSizeMultiplier);

      Request thumbnailRequest =
          obtainRequest(
              target,
              targetListener,
              thumbnailOptions,
              coordinator,
              transitionOptions,
              getThumbnailPriority(priority),
              overrideWidth,
              overrideHeight);

      coordinator.setRequests(fullRequest, thumbnailRequest);
      return coordinator;
    } else {
      // Base case: no thumbnail.
      return obtainRequest(
          target,
          targetListener,
          requestOptions,
          parentCoordinator,
          transitionOptions,
          priority,
          overrideWidth,
          overrideHeight);
    }
  }

從上面代碼可以看出,它分為三種請求,一種包含縮略圖的請求但是遞回呼叫的,一種包含縮略圖請求直接請求的,一種不含縮略圖的請求,但是他們三個最終呼叫了SingleRequest.obtain()方法:

   return SingleRequest.obtain(
        context,
        glideContext,
        model,
        transcodeClass,
        requestOptions,
        overrideWidth,
        overrideHeight,
        priority,
        target,
        targetListener,
        requestListener,
        requestCoordinator,
        glideContext.getEngine(),
        transitionOptions.getTransitionFactory());
  }

再往里看就是一個init方法,對請求各種引數的初始化:

 private void init(
      Context context,
      GlideContext glideContext,
      Object model,
      Class<R> transcodeClass,
      RequestOptions requestOptions,
      int overrideWidth,
      int overrideHeight,
      Priority priority,
      Target<R> target,
      RequestListener<R> targetListener,
      RequestListener<R> requestListener,
      RequestCoordinator requestCoordinator,
      Engine engine,
      TransitionFactory<? super R> animationFactory) {
    this.context = context;
    this.glideContext = glideContext;
    this.model = model;
    this.transcodeClass = transcodeClass;
    this.requestOptions = requestOptions;
    this.overrideWidth = overrideWidth;
    this.overrideHeight = overrideHeight;
    this.priority = priority;
    this.target = target;
    this.targetListener = targetListener;
    this.requestListener = requestListener;
    this.requestCoordinator = requestCoordinator;
    this.engine = engine;
    this.animationFactory = animationFactory;
    status = Status.PENDING;
  }

分析到這里我們發現,request請求構造完畢,接下來何時開始請求的呢?

我們回到最前面的into()方法里面,接著往下看,我們會發現,有兩處地方,一處是previous.begin(),一處是requestManager.track(target, request),前者是復用上一個請求直接開始請求,后者是呼叫了RequestTracker.runRequest()方法:

  public void runRequest(@NonNull Request request) {
    requests.add(request);
    if (!isPaused) {
      request.begin();
    } else {
      pendingRequests.add(request);
    }
  }

首先將request添加到一個佇列里面,如果當前不是pause狀態,開始請求,否則加入待請求佇列,(這里的佇列不是說存盤結構是佇列),

請求開始的地方找到了,我們之前構造請求分析到最終呼叫SingleRequest.init()方法,SingleRequest是request介面實作類,request.begin(),其實最侄訓回呼SingleRequest.begin()方法:

  public void begin() {
    ...
    // 圖片資源為空拋例外
    if (model == null) {
      if (Util.isValidDimensions(overrideWidth, overrideHeight)) {
        width = overrideWidth;
        height = overrideHeight;
      }
      // Only log at more verbose log levels if the user has set a fallback drawable, because
      // fallback Drawables indicate the user expects null models occasionally.
      int logLevel = getFallbackDrawable() == null ? Log.WARN : Log.DEBUG;
      onl oadFailed(new GlideException("Received null model"), logLevel);
      return;
    }

    if (status == Status.RUNNING) {
      throw new IllegalArgumentException("Cannot restart a running request");
    }

    // If we're restarted after we're complete (usually via something like a notifyDataSetChanged
    // that starts an identical request into the same Target or View), we can simply use the
    // resource and size we retrieved the last time around and skip obtaining a new size, starting a
    // new load etc. This does mean that users who want to restart a load because they expect that
    // the view size has changed will need to explicitly clear the View or Target before starting
    // the new load.
    // 圖片加載完成,釋放資源
    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.
    // 新的請求從獲取圖片size開始
    status = Status.WAITING_FOR_SIZE;
    if (Util.isValidDimensions(overrideWidth, overrideHeight)) {
      onSizeReady(overrideWidth, overrideHeight);
    } else {
      target.getSize(this);
    }
    // 通知加載圖片開始
    if ((status == Status.RUNNING || status == Status.WAITING_FOR_SIZE)
        && canNotifyStatusChanged()) {
      target.onLoadStarted(getPlaceholderDrawable());
    }
    if (IS_VERBOSE_LOGGABLE) {
      logV("finished run method in " + LogTime.getElapsedMillis(startTime));
    }
  }

我們看上面代碼會發現,一個新的請求是從onSizeReady()開始的:

public void onSizeReady(int width, int height) {
    ...
    
    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);

    // This is a hack that's only useful for testing right now where loads complete synchronously
    // even though under any executor running on any thread but the main thread, the load would
    // have completed asynchronously.
    if (status != Status.RUNNING) {
      loadStatus = null;
    }
    if (IS_VERBOSE_LOGGABLE) {
      logV("finished onSizeReady in " + LogTime.getElapsedMillis(startTime));
    }
  }

我們看里面會呼叫一個engine.load()方法,engine干嘛的呢,我們進入Engine這個類,可以看到注釋描述是負責加載圖片和管理快取的,我們接下來看一下這個load()方法具體實作:

  public <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) {
    Util.assertMainThread();
    long startTime = LogTime.getLogTime();

    // 生成快取的key
    EngineKey key = keyFactory.buildKey(model, signature, width, height, transformations,
        resourceClass, transcodeClass, options);
    // 從活動快取獲取
    EngineResource<?> active = loadFromActiveResources(key, isMemoryCacheable);
    if (active != null) {
      cb.onResourceReady(active, DataSource.MEMORY_CACHE);
      if (Log.isLoggable(TAG, Log.VERBOSE)) {
        logWithTimeAndKey("Loaded resource from active resources", startTime, key);
      }
      return null;
    }
    // 從記憶體快取LruCache獲取
    EngineResource<?> cached = loadFromCache(key, isMemoryCacheable);
    if (cached != null) {
      cb.onResourceReady(cached, DataSource.MEMORY_CACHE);
      if (Log.isLoggable(TAG, Log.VERBOSE)) {
        logWithTimeAndKey("Loaded resource from cache", startTime, key);
      }
      return null;
    }
    // 開啟執行緒從磁盤獲取快取
    EngineJob<?> current = jobs.get(key, onlyRetrieveFromCache);
    if (current != null) {
      current.addCallback(cb);
      if (Log.isLoggable(TAG, Log.VERBOSE)) {
        logWithTimeAndKey("Added to existing load", startTime, key);
      }
      return new LoadStatus(cb, current);
    }

    EngineJob<R> engineJob =
        engineJobFactory.build(
            key,
            isMemoryCacheable,
            useUnlimitedSourceExecutorPool,
            useAnimationPool,
            onlyRetrieveFromCache);

    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);
    // 通過執行緒池開啟一個執行緒
    engineJob.start(decodeJob);

    if (Log.isLoggable(TAG, Log.VERBOSE)) {
      logWithTimeAndKey("Started new load", startTime, key);
    }
    return new LoadStatus(cb, engineJob);
  }

看到這里我們會驚喜的發現有兩個方法loadFromActiveResources()、loadFromCache(),這不就是我們想要獲取快取的方法嗎,我們先看loadFromActiveResources()方法:

  private EngineResource<?> loadFromActiveResources(Key key, boolean isMemoryCacheable) {
    // 不使用記憶體快取直接回傳null
    if (!isMemoryCacheable) {
      return null;
    }
    // 通過key取出快取
    EngineResource<?> active = activeResources.get(key);
    if (active != null) {
      // 參考計數+1
      active.acquire();
    }

    return active;
  }

我們從上面可以看到兩個方法一個獲取快取的get()方法,一個是acquire()方法,分別看下實作:

 EngineResource<?> get(Key key) {
    ResourceWeakReference activeRef = activeEngineResources.get(key);
    if (activeRef == null) {
      return null;
    }

    EngineResource<?> active = activeRef.get();
    if (active == null) {
      cleanupActiveReference(activeRef);
    }
    return active;
  }

  void acquire() {
    if (isRecycled) {
      throw new IllegalStateException("Cannot acquire a recycled resource");
    }
    if (!Looper.getMainLooper().equals(Looper.myLooper())) {
      throw new IllegalThreadStateException("Must call acquire on the main thread");
    }
    ++acquired;
  }

我們從上面代碼可以看出我們使用一個弱參考存盤我們的活動快取,然后用一個計數器來標記是否正在使用,每參考一次+1,相反release時候-1,最后acquired=0時,回收我們的活動快取,

  void release() {
    if (acquired <= 0) {
      throw new IllegalStateException("Cannot release a recycled or not yet acquired resource");
    }
    if (!Looper.getMainLooper().equals(Looper.myLooper())) {
      throw new IllegalThreadStateException("Must call release on the main thread");
    }
    if (--acquired == 0) {
      listener.onResourceReleased(key, this);
    }
  }

接下來我們看一下loadFromCache()方法,如下:

  private EngineResource<?> loadFromCache(Key key, boolean isMemoryCacheable) {
    if (!isMemoryCacheable) {
      return null;
    }
    // 從Lrucahe取出快取,并從中移除
    EngineResource<?> cached = getEngineResourceFromCache(key);
    // 將快取存入弱參考中
    if (cached != null) {
      cached.acquire();
      activeResources.activate(key, cached);
    }
    return cached;
  }

  private EngineResource<?> getEngineResourceFromCache(Key key) {
    Resource<?> cached = cache.remove(key);

    final EngineResource<?> result;
    if (cached == null) {
      result = null;
    } else if (cached instanceof EngineResource) {
      // Save an object allocation if we've cached an EngineResource (the typical case).
      result = (EngineResource<?>) cached;
    } else {
      result = new EngineResource<>(cached, true /*isMemoryCacheable*/, true /*isRecyclable*/);
    }
    return result;
  }

  void activate(Key key, EngineResource<?> resource) {
    ResourceWeakReference toPut =
        new ResourceWeakReference(
            key,
            resource,
            getReferenceQueue(),
            isActiveResourceRetentionAllowed);

    ResourceWeakReference removed = activeEngineResources.put(key, toPut);
    if (removed != null) {
      removed.reset();
    }
  }

我們可以看到他是先從LruCache獲取快取并從Lrucache中移除,然后在放入弱參考中保存,完成快取從LruCache到弱參考的轉移,

接著engine.load()方法往下看,我們可以看到分別創建了一個EngineJob、DecodeJob,EngineJob是負責管理加載成功、失敗的回呼,DecodeJob是一個執行緒,負責獲取磁盤快取,

Engine#load方法:    engineJob.addCallback(cb);
             engineJob.start(decodeJob);
  
// 添加加載完成的回呼
void addCallback(ResourceCallback cb) {
    Util.assertMainThread();
    stateVerifier.throwIfRecycled();
    if (hasResource) {
      cb.onResourceReady(engineResource, dataSource);
    } else if (hasLoadFailed) {
      cb.onLoadFailed(exception);
    } else {
      cbs.add(cb);
    }
  }
  // 開啟一個執行緒
  public void start(DecodeJob<R> decodeJob) {
    this.decodeJob = decodeJob;
    GlideExecutor executor = decodeJob.willDecodeFromCache()
        ? diskCacheExecutor
        : getActiveSourceExecutor();
    executor.execute(decodeJob);
  }


我們知道一個執行緒開啟后,運行的方法是run(),so我們看看DecodeJob的run()方法

  public void run() {
 
    DataFetcher<?> localFetcher = currentFetcher;
    try {
      // 如果取消了,直接通知錯誤
      if (isCancelled) {
        notifyFailed();
        return;
      }
      // 根據策略加載不同的快取
      runWrapped();
    } catch (Throwable t) {

      if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "DecodeJob threw unexpectedly"
            + ", isCancelled: " + isCancelled
            + ", stage: " + stage, t);
      }
      // When we're encoding we've already notified our callback and it isn't safe to do so again.
      if (stage != Stage.ENCODE) {
        throwables.add(t);
        notifyFailed();
      }
      if (!isCancelled) {
        throw t;
      }
    } finally {
      // 最后呼叫clean方法
      if (localFetcher != null) {
        localFetcher.cleanup();
      }
      TraceCompat.endSection();
    }
  }

從上面的代碼可以看出主要是呼叫了runWrapped()方法,這個方法主要是根據不同的策略加載不同型別的磁盤快取,在分析代碼之前我們先回顧一下Glide支持哪幾種磁盤快取?

Glide5大磁盤快取策略
DiskCacheStrategy.DATA: 只快取原始圖片;
DiskCacheStrategy.RESOURCE:只快取轉換過后的圖片;
DiskCacheStrategy.ALL:既快取原始圖片,也快取轉換過后的圖片;對于遠程圖片,快取 DATARESOURCE;對于本地圖片,只快取 RESOURCE
DiskCacheStrategy.NONE:不快取任何內容;
DiskCacheStrategy.AUTOMATIC:默認策略,嘗試對本地和遠程圖片使用最佳的策略,當下載網路圖片時,使用DATA;對于本地圖片,使用RESOURCE

從上面可以知道,Glide支持5種磁盤快取策略,接著看runWrapped()方法實作:

  private void runWrapped() {
    switch (runReason) {
      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);
    }
  }

我們從上面代碼可以看出主要呼叫了3個方法 getNextStage()、getNextGenerator()、runGenerators():

  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;
    while (!isCancelled && currentGenerator != null
        && !(isStarted = currentGenerator.startNext())) {
      stage = getNextStage(stage);
      currentGenerator = getNextGenerator();

      if (stage == Stage.SOURCE) {
        reschedule();
        return;
      }
    }
    // We've run out of stages and generators, give up.
    if ((stage == Stage.FINISHED || isCancelled) && !isStarted) {
      notifyFailed();
    }
  }

依次往下看getNextStage()方法會根據當前Stage的狀態回傳下一個Stage狀態,然后getNextGenerator()會根據當前的Stage狀態回傳對應的快取生成器,然后執行runGenerators()方法,里面呼叫了快取生成器的startNext()方法,回圈執行getNextStage()getNextGenerator()方法,最后當前stage是Stage.SOURCE跳出當前回圈,如果我們第一次從網路加載圖片,由于Stage最開始狀態是INITIALIZE,最終呼叫的是SouceGenerator,如果有磁盤快取時,呼叫DataCacheGeneratorResouceCacheGenerator

  • ResourceCacheGenerator: 變換之后的資料快取生成器,
  • DataCacheGenerator:直接從網路獲取的資料快取生成器,
  • SourceGenerator: 未經變換原始資料快取生成器,

我們在SouceGenerator的StartNext()可以看到:

  public boolean startNext() {
    // 如果有快取,從快取中獲取
    if (dataToCache != null) {
      Object data = dataToCache;
      dataToCache = null;
      cacheData(data);
    }
    // 呼叫DataCacheGenerator startNext()方法
    if (sourceCacheGenerator != null && sourceCacheGenerator.startNext()) {
      return true;
    }
    sourceCacheGenerator = null;

    loadData = null;
    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;
        // 從網路加載資料
        loadData.fetcher.loadData(helper.getPriority(), this);
      }
    }
    return started;
  }

從上面代碼可以看出SouceGenerator.StartNext()方法先會判斷當前是否有快取,由于第一次從網路加載圖片是沒有快取的,最終呼叫的是fetcher.loadData()方法,通過HttpUrlFetcher實作的,代碼如下:

  @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());
      // 請求完成回呼
      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));
      }
    }
  }

請求完成通過onDataReady()回呼-->到SourceGenerator.onDataFetcherReady()方法先保存資料:

  @Override
  public void onDataReady(Object data) {
    DiskCacheStrategy diskCacheStrategy = helper.getDiskCacheStrategy();
    if (data != null && diskCacheStrategy.isDataCacheable(loadData.fetcher.getDataSource())) {
      // 保存資料
      dataToCache = data;
      // We might be being called back on someone else's thread. Before doing anything, we should
      // reschedule to get back onto Glide's thread.
      // 回呼
      cb.reschedule();
    } else {
      cb.onDataFetcherReady(loadData.sourceKey, data, loadData.fetcher,
          loadData.fetcher.getDataSource(), originalKey);
    }
  }

通過回呼,最終通過DecodeJob#run()方法通過decodeFromRetrievedData()方法呼叫notifyEncodeAndRelease()方法

  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();
    }
  }

最后到handleResultOnMainThread()方法完成加載圖片,并通過弱參考寫入快取:

  @Synthetic
  void handleResultOnMainThread() {
    stateVerifier.throwIfRecycled();
    if (isCancelled) {
      resource.recycle();
      release(false /*isRemovedFromQueue*/);
      return;
    } else if (cbs.isEmpty()) {
      throw new IllegalStateException("Received a resource without any callbacks to notify");
    } else if (hasResource) {
      throw new IllegalStateException("Already have resource");
    }
    engineResource = engineResourceFactory.build(resource, isCacheable);
    hasResource = true;

    // Hold on to resource for duration of request so we don't recycle it in the middle of
    // notifying if it synchronously released by one of the callbacks.
    engineResource.acquire();
    // 圖片請求完成,并寫入快取
    listener.onEngineJobComplete(this, key, engineResource);

    //noinspection ForLoopReplaceableByForEach to improve perf
    for (int i = 0, size = cbs.size(); i < size; i++) {
      ResourceCallback cb = cbs.get(i);
      if (!isInIgnoredCallbacks(cb)) {
        engineResource.acquire();
        cb.onResourceReady(engineResource, dataSource);
      }
    }
    // Our request is complete, so we can release the resource.
    engineResource.release();

    release(false /*isRemovedFromQueue*/);
  }


 public void onEngineJobComplete(EngineJob<?> engineJob, Key key, EngineResource<?> resource) {
    Util.assertMainThread();
    // A null resource indicates that the load failed, usually due to an exception.
    if (resource != null) {
      resource.setResourceListener(key, this);

      if (resource.isCacheable()) {
        activeResources.activate(key, resource);
      }
    }

    jobs.removeIfCurrent(key, engineJob);
  }

我們第一次從網路加載圖片是通過SouceGenerator從網路獲取顯示并寫入快取,我們再看看DataCacheGenerator、ResouceCacheGenerator快取獲取,

public boolean startNext() {
    List<Key> sourceIds = helper.getCacheKeys();
    if (sourceIds.isEmpty()) {
      return false;
    }
    List<Class<?>> resourceClasses = helper.getRegisteredResourceClasses();
    if (resourceClasses.isEmpty()) {
      if (File.class.equals(helper.getTranscodeClass())) {
        return false;
      }
      throw new IllegalStateException(
          "Failed to find any load path from " + helper.getModelClass() + " to "
              + helper.getTranscodeClass());
    }
    while (modelLoaders == null || !hasNextModelLoader()) {
      resourceClassIndex++;
      if (resourceClassIndex >= resourceClasses.size()) {
        sourceIdIndex++;
        if (sourceIdIndex >= sourceIds.size()) {
          return false;
        }
        resourceClassIndex = 0;
      }

      Key sourceId = sourceIds.get(sourceIdIndex);
      Class<?> resourceClass = resourceClasses.get(resourceClassIndex);
      Transformation<?> transformation = helper.getTransformation(resourceClass);
     
      // 獲取快取Key
      currentKey =
          new ResourceCacheKey(// NOPMD AvoidInstantiatingObjectsInLoops
              helper.getArrayPool(),
              sourceId,
              helper.getSignature(),
              helper.getWidth(),
              helper.getHeight(),
              transformation,
              resourceClass,
              helper.getOptions());
      // 讀取快取
      cacheFile = helper.getDiskCache().get(currentKey);
      if (cacheFile != null) {
        sourceKey = sourceId;
        modelLoaders = helper.getModelLoaders(cacheFile);
        modelLoaderIndex = 0;
      }
    }

    loadData = null;
    boolean started = false;
    while (!started && hasNextModelLoader()) {
      ModelLoader<File, ?> modelLoader = modelLoaders.get(modelLoaderIndex++);
      loadData = modelLoader.buildLoadData(cacheFile,
          helper.getWidth(), helper.getHeight(), helper.getOptions());
      if (loadData != null && helper.hasLoadPath(loadData.fetcher.getDataClass())) {
        started = true;
        // 網路加載
        loadData.fetcher.loadData(helper.getPriority(), this);
      }
    }

    return started;
  }

大概流程:先獲取快取key,然后取出快取,如果快取不存在,通過網路重新獲取,

至此,終于將Glide快取原理全部分析完畢,總結一下,

小結1

Glide總共有2級快取,一級記憶體快取包括弱參考活動快取、LruCache快取,二級DiskLruCache,第一次從網路加載圖片時,會開啟執行緒從網路下載圖片,下載完成后保存到磁盤,然后再加入弱參考快取,下次加載圖片會先從弱參考獲取,弱參考維護一個acquired引數,判斷當前圖片是否正在使用,每load一次+1,每release一次-1,如果acquired == 0時,代表圖片不在使用,回收弱參考物件并把快取寫入LruCache,如果從弱參考獲取不到快取,就會從LruCache獲取快取,并將從當前佇列移除,放入弱參考保存,最后如果LruCache也獲取不到快取,從磁盤獲取快取,如果磁盤快取不存在,就會重新從網路加載圖片,

2.生命周期處理

Glide生命周期相比快取處理,要簡單不少,下面通過原始碼簡單介紹一下,

熟悉Glide的同學應該知道,Glide是通過Glide.With("xxx")傳入生命周期:

大概有5個構造方法,和之前一樣隨便點進去一個去看:

  @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);
  }

我們發現其實你傳入無論是fragment還是activity還是view context主要分為兩種一種是Application、一種非Application,我們先看下Application的,回傳的是getApplicationManager(context):


  @NonNull
  private RequestManager getApplicationManager(@NonNull Context context) {
    // Either an application context or we're on a background thread.
    if (applicationManager == null) {
      synchronized (this) {
        if (applicationManager == null) {

          // TODO(b/27524013): Factor out this Glide.get() call.
          Glide glide = Glide.get(context.getApplicationContext());
          applicationManager =
              factory.build(
                  glide,
                  new ApplicationLifecycle(),
                  new EmptyRequestManagerTreeNode(),
                  context.getApplicationContext());
        }
      }
    }

    return applicationManager;
  }

從上面代碼可以看出關聯的是app生命周期,和應用的生命周期一致,我們再看非Application,根據是否support包下區分為

fragmentGet()、supportFragmentGet()方法:
  private RequestManager supportFragmentGet(@NonNull Context context, @NonNull FragmentManager fm,
      @Nullable Fragment parentHint) {
    // 創建一個空白fragment
    SupportRequestManagerFragment current = getSupportRequestManagerFragment(fm, parentHint);
    RequestManager requestManager = current.getRequestManager();
    if (requestManager == null) {
      // glide關聯fragment的生命周期
      Glide glide = Glide.get(context);
      requestManager =
          factory.build(
              glide, current.getGlideLifecycle(), current.getRequestManagerTreeNode(), context);
      current.setRequestManager(requestManager);
    }
    return requestManager;
  }

  @NonNull
  private RequestManager fragmentGet(@NonNull Context context,
      @NonNull android.app.FragmentManager fm,
      @Nullable android.app.Fragment parentHint) {
    // 創建一個空白fragment
    RequestManagerFragment current = getRequestManagerFragment(fm, parentHint);
    RequestManager requestManager = current.getRequestManager();
    if (requestManager == null) {
      // TODO(b/27524013): Factor out this Glide.get() call.
      Glide glide = Glide.get(context);
     // glide關聯fragment的生命周期
      requestManager =
          factory.build(
              glide, current.getGlideLifecycle(), current.getRequestManagerTreeNode(), context);
      current.setRequestManager(requestManager);
    }
    return requestManager;
  }

我們可以看到他們首先都會創建一個空白fragment,然后和Glide關聯起來,

  RequestManagerFragment getRequestManagerFragment(
      @NonNull final android.app.FragmentManager fm, @Nullable android.app.Fragment parentHint) {
    // 先根據tag查找是否存在
    RequestManagerFragment current = (RequestManagerFragment) fm.findFragmentByTag(FRAGMENT_TAG);
    if (current == null) {
      如果為空從map中取出
      current = pendingRequestManagerFragments.get(fm);
      if (current == null) {
        // 創建一個空白fragment
        current = new RequestManagerFragment();
        current.setParentFragmentHint(parentHint);
        // 放入map里面
        pendingRequestManagerFragments.put(fm, current);
        // 添加之前創建的空白fragment
        fm.beginTransaction().add(current, FRAGMENT_TAG).commitAllowingStateLoss();
        // 通知map移除剛添加的fragment
        handler.obtainMessage(ID_REMOVE_FRAGMENT_MANAGER, fm).sendToTarget();
      }
    }
    return current;
  }

我們進入RequestManagerFragment會發現,創建的時候,會默認構造一個ActivityFragmentLifecycle:

  public RequestManagerFragment() {
    this(new ActivityFragmentLifecycle());
  }


class ActivityFragmentLifecycle implements Lifecycle {
 
   // 省略代碼...
  @Override
  public void addListener(@NonNull LifecycleListener listener) {
    lifecycleListeners.add(listener);

    if (isDestroyed) {
      listener.onDestroy();
    } else if (isStarted) {
      listener.onStart();
    } else {
      listener.onStop();
    }
  }

  @Override
  public void removeListener(@NonNull LifecycleListener listener) {
    lifecycleListeners.remove(listener);
  }

  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();
    }
  }
}

其中宣告了onStart()、onStop()、onDestroy()方法,我們再看RequestManagerFragment里面對應的onStart()、onStop()、onDestroy()方法:

#RequestManagerFragment

  @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();
  }

會發現fragment周期方法回呼的時候會回呼ActivityFragmentLifecycle的方法,然后遍歷所有LifecycleListener,LifecycleListener是什么呢?

public interface LifecycleListener {

  /**
   * Callback for when {@link android.app.Fragment#onStart()}} or {@link
   * android.app.Activity#onStart()} is called.
   */
  void onStart();

  /**
   * Callback for when {@link android.app.Fragment#onStop()}} or {@link
   * android.app.Activity#onStop()}} is called.
   */
  void onStop();

  /**
   * Callback for when {@link android.app.Fragment#onDestroy()}} or {@link
   * android.app.Activity#onDestroy()} is called.
   */
  void onDestroy();
}

其實就是Glide定義生命周期相關介面,通過介面回呼,來控制暫停、恢復加載、移除相關操作,

小結2

總結一下,Glide生命周期和Activity、Fragment關聯,是通過with方法傳入引數,如果是Application context就與app的生命周期關聯起來,如果非Application context 先判斷是否是后臺執行緒,會轉為Application context方法,繼續執行,如果不是就會通過創建一個空白fragment,并構造一個ActivityFragmentLifecycle介面,fragment生命周期方法呼叫時,ActivityFragmentLifecycle中的介面方法會呼叫并回呼到Glide LifecycleListener介面,從而實作了和fragment生命周期管理起來,


總結

至此,終于全部分析完了,本文描述了Glide、Fresco、Picasso對比,著重從原始碼分析了一下Glide快取和生命周期原理,由于個人水平有限,有誤的地方敬請指出,謝謝,

Thanks:

Android 【手撕Glide】--Glide快取機制

創作不易,如果覺得有用的話,麻煩點個贊,

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/184732.html

標籤:其他

上一篇:關于uni-app中云打包成apk包在手機上運行無法使用uni.getLocation獲取定位

下一篇:appium移動端自動化測驗

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • vue移動端上拉加載

    可能做得過于簡單或者比較low,請各位大佬留情,一起探討技術 ......

    uj5u.com 2020-09-10 04:38:07 more
  • 優美網站首頁,頂部多層導航

    一個個人用的瀏覽器首頁,可以把一下常用的網站放在這里,平常打開會比較方便。 第一步,HTML代碼 <script src=https://www.cnblogs.com/szharf/p/"js/jquery-3.4.1.min.js"></script> <div id="navigate"> <ul> <li class="labels labels_1"> ......

    uj5u.com 2020-09-10 04:38:47 more
  • 頁面為要加<!DOCTYPE html>

    最近因為寫一個js函式,需要用到$(window).height(); 由于手寫demo的時候,過于自信,其實對前端方面的認識也不夠體系,用文本檔案直接敲出來的html代碼,第一行沒有加上<!DOCTYPE html> 導致了$(window).height();的結果直接是整個document的高 ......

    uj5u.com 2020-09-10 04:38:52 more
  • WordPress網站程式手動升級要做好資料備份

    WordPress博客網站程式在進行升級前,必須要做好網站資料的備份,這個問題良家佐言是遇見過的;在剛開始接觸WordPress博客程式的時候,因為升級問題和博客網站的修改的一些嘗試,良家佐言是吃盡了苦頭。因為購買的是西部數碼的空間和域名,每當佐言把自己的WordPress博客網站搞到一塌糊涂的時候 ......

    uj5u.com 2020-09-10 04:39:30 more
  • WordPress程式不能升級為5.4.2版本的原因

    WordPress是一款個人博客系統,受到英文博客愛好者和中文博客愛好者的追捧,并逐步演化成一款內容管理系統軟體;它是使用PHP語言和MySQL資料庫開發的,用戶可以在支持PHP和MySQL資料庫的服務器上使用自己的博客。每一次WordPress程式的更新,就會牽動無數WordPress愛好者的心, ......

    uj5u.com 2020-09-10 04:39:49 more
  • 使用CSS3的偽元素進行首字母下沉和首行改變樣式

    網頁中常見的一種效果,首字改變樣式或者首行改變樣式,效果如下圖。 代碼: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, ......

    uj5u.com 2020-09-10 04:40:09 more
  • 關于a標簽的講解

    什么是a標簽? <a> 標簽定義超鏈接,用于從一個頁面鏈接到另一個頁面。 <a> 元素最重要的屬性是 href 屬性,它指定鏈接的目標。 a標簽的語法格式:<a href=https://www.cnblogs.com/summerxbc/p/"指定要跳轉的目標界面的鏈接">需要展示給用戶看見的內容</a> a標簽 在所有瀏覽器中,鏈接的默認外觀如下: 未被訪問的鏈接帶 ......

    uj5u.com 2020-09-10 04:40:11 more
  • 前端輪播圖

    在需要輪播的頁面是引入swiper.min.js和swiper.min.css swiper.min.js地址: 鏈接:https://pan.baidu.com/s/15Uh516YHa4CV3X-RyjEIWw 提取碼:4aks swiper.min.css地址 鏈接:https://pan.b ......

    uj5u.com 2020-09-10 04:40:13 more
  • 如何設定html中的背景圖片(全屏顯示,且不拉伸)

    1 <style>2 body{background-image:url(https://uploadbeta.com/api/pictures/random/?key=BingEverydayWallpaperPicture); 3 background-size:cover;background ......

    uj5u.com 2020-09-10 04:40:16 more
  • Java學習——HTML詳解(上)

    HTML詳解 初識HTML Hyper Text Markup Language(超文本標記語言) 1 <!--DOCTYPE:告訴瀏覽器我們要使用什么規范--> 2 <!DOCTYPE html> 3 <html lang="en"> 4 <head> 5 <!--meta 描述性的標簽,描述一些 ......

    uj5u.com 2020-09-10 04:40:33 more
最新发布
  • 我的第一個NPM包:panghu-planebattle-esm(胖虎飛機大戰)使用說明

    好家伙,我的包終于開發完啦 歡迎使用胖虎的飛機大戰包!! 為你的主頁添加色彩 這是一個有趣的網頁小游戲包,使用canvas和js開發 使用ES6模塊化開發 效果圖如下: (覺得圖片太sb的可以自己改) 代碼已開源!! Git: https://gitee.com/tang-and-han-dynas ......

    uj5u.com 2023-04-20 07:59:23 more
  • 生產事故-走近科學之消失的JWT

    入職多年,面對生產環境,盡管都是小心翼翼,慎之又慎,還是難免捅出簍子。輕則滿頭大汗,面紅耳赤。重則系統停擺,損失資金。每一個生產事故的背后,都是寶貴的經驗和教訓,都是專案成員的血淚史。為了更好地防范和遏制今后的各類事故,特開此專題,長期更新和記錄大大小小的各類事故。有些是親身經歷,有些是經人耳傳口授 ......

    uj5u.com 2023-04-18 07:55:04 more
  • 記錄--Canvas實作打飛字游戲

    這里給大家分享我在網上總結出來的一些知識,希望對大家有所幫助 打開游戲界面,看到一個畫面簡潔、卻又富有挑戰性的游戲。螢屏上,有一個白色的矩形框,里面不斷下落著各種單詞,而我需要迅速地輸入這些單詞。如果我輸入的單詞與螢屏上的單詞匹配,那么我就可以獲得得分;如果我輸入的單詞錯誤或者時間過長,那么我就會輸 ......

    uj5u.com 2023-04-04 08:35:30 more
  • 了解 HTTP 看這一篇就夠

    在學習網路之前,了解它的歷史能夠幫助我們明白為何它會發展為如今這個樣子,引發探究網路的興趣。下面的這張圖片就展示了“互聯網”誕生至今的發展歷程。 ......

    uj5u.com 2023-03-16 11:00:15 more
  • 藍牙-低功耗中心設備

    //11.開啟藍牙配接器 openBluetoothAdapter //21.開始搜索藍牙設備 startBluetoothDevicesDiscovery //31.開啟監聽搜索藍牙設備 onBluetoothDeviceFound //30.停止監聽搜索藍牙設備 offBluetoothDevi ......

    uj5u.com 2023-03-15 09:06:45 more
  • canvas畫板(滑鼠和觸摸)

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>canves</title> <style> #canvas { cursor:url(../images/pen.png),crosshair; } #canvasdiv{ bo ......

    uj5u.com 2023-02-15 08:56:31 more
  • 手機端H5 實作自定義拍照界面

    手機端 H5 實作自定義拍照界面也可以使用 MediaDevices API 和 <video> 標簽來實作,和在桌面端做法基本一致。 首先,使用 MediaDevices.getUserMedia() 方法獲取攝像頭媒體流,并將其傳遞給 <video> 標簽進行渲染。 接著,使用 HTML 的 < ......

    uj5u.com 2023-01-12 07:58:22 more
  • 記錄--短視頻滑動播放在 H5 下的實作

    這里給大家分享我在網上總結出來的一些知識,希望對大家有所幫助 短視頻已經無數不在了,但是主體還是使用 app 來承載的。本文講述 H5 如何實作 app 的視頻滑動體驗。 無聲勝有聲,一圖頂百辯,且看下圖: 網址鏈接(需在微信或者手Q中瀏覽) 從上圖可以看到,我們主要實作的功能也是本文要講解的有: ......

    uj5u.com 2023-01-04 07:29:05 more
  • 一文讀懂 HTTP/1 HTTP/2 HTTP/3

    從 1989 年萬維網(www)誕生,HTTP(HyperText Transfer Protocol)經歷了眾多版本迭代,WebSocket 也在期間萌芽。1991 年 HTTP0.9 被發明。1996 年出現了 HTTP1.0。2015 年 HTTP2 正式發布。2020 年 HTTP3 或能正... ......

    uj5u.com 2022-12-24 06:56:02 more
  • 【HTML基礎篇002】HTML之form表單超詳解

    ??一、form表單是什么

    ??二、form表單的屬性

    ??三、input中的各種Type屬性值

    ??四、標簽 ......

    uj5u.com 2022-12-18 07:17:06 more