Picasso框架的基本使用方法

Picasso流程图:
Picasso框架的基本使用方法_第1张图片

Picasso: Image downloading, transformation, and caching manager(图片下载,改变,缓存管理器)
load: 加载目标(图片)地址
into:将图片加载到目标控件进行显示

Picasso类主要方法:
cancelRequest(Target target) 取消请求
cancelTag(Object tag) 根据tag取消请求
cancelRequest(ImageView view) 取消请求
三种方法无本质区别,最终都会调用cancelExistingRequest(Object target)

Dispatcher: 任务调度器
dispatchSubmit(Action action)
dispatchCancel(Action action)
dispatchPauseTag(Object tag)
dispatchResumeTag(Object tag)
dispatchComplete(BitmapHunter hunter)
dispatchRetry(BitmapHunter hunter)
dispatchFailed(BitmapHunter hunter)
dispatchNetworkStateChange(NetworkInfo info)
dispatchAirplaneModeChange(boolean airplaneMode)
performSubmit(Action action)

上面的dispatchxxx的方法,内部只是通过handler发送了一条消息,而最终都会执行performXXX方法.

BtimapHunter: 一个Runnable,其中有一个decode的抽象方法,用于子类实现不同类型资源的解析。
内部会调用hunt方法,本质是获取Bitmap对象,然后通过Dispatcher进行分发。

Action:抽象类,代表了一个具体的加载任务,主要用于图片加载后的结果回调,有两个抽象方法,complete和error,也就是当图片解析为bitmap后用户希望做什么。最简单的就是将bitmap设置给imageview,失败了就将错误通过回调通知到上层。

Cache类:Picasso内部采用了LRUCache类进行内存缓存处理,最大内存分配值为当前手机可用内存的1/7.将近15%。
Picasso的文件缓存,目录在当前的应用的目录下面的picasso-cache这个文件夹下面,默认文件缓存最大不能超过50M,最小不低于5M,当然,如果当前手机的可用的本地存储小于5M,那么已当前手机的所剩的本地存储的大小作为文件缓存的大小。

ResourceRequestHandler FileRequestHandler NetworkRequestHandler
这3个类主要是根据资源的不同进行相应的处理
NetworkRequestHandler:
发送网络请求,返回inputstream,结果返回到BitmapHunter中
其余2个类,原理差不多,只是对象不一样。

RequestCreator: Fluent API for building an image download request. 主要是用来构造一个图片的下载请求的一个api。(通过链式调用)

流程分析

Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

下面我就来分析一下这句代码是如何实现加载网络图片的:

//主流程1
 public static Picasso with(Context context) {
    if (singleton == null) {
      synchronized (Picasso.class) {
        if (singleton == null) {
            //指向分流程1
          singleton = new Builder(context).build();
        }
      }
    }
    return singleton;
  }

通过上面代码,我们可以知道Picasso.With()方法只是采用单例模式初始化了一个Picasso对象。

//分流程1
 public Picasso build() {
      Context context = this.context;

      if (downloader == null) {
        //创建下载器
        downloader = Utils.createDefaultDownloader(context);
      }
      if (cache == null) {
        //创建LruCache缓存
        cache = new LruCache(context);
      }
      if (service == null) {
        //创建执行任务
        service = new PicassoExecutorService();
      }
      if (transformer == null) {
        transformer = RequestTransformer.IDENTITY;
      }

      Stats stats = new Stats(cache);
      //创建任务调度器
      Dispatcher dispatcher = new Dispatcher(context, service, HANDLER, downloader, cache, stats);

      return new Picasso(context, dispatcher, cache, listener, transformer, requestHandlers, stats,
          defaultBitmapConfig, indicatorsEnabled, loggingEnabled);
    }
  }

通过build()方法可知,在创建Picasso对象过程中,进行了一系列初始化,缓存,下载器,任务调度器等。

    //主流程2
  public RequestCreator load(String path) {
    if (path == null) {
      return new RequestCreator(this, null, 0);
    }
    if (path.trim().length() == 0) {
      throw new IllegalArgumentException("Path must not be empty.");
    }
    //指向分流程2
    return load(Uri.parse(path));
  }

    //分流程2
  public RequestCreator load(Uri uri) {
    //指向分流程3
    return new RequestCreator(this, uri, 0);
  }

    //分流程3
   RequestCreator(Picasso picasso, Uri uri, int resourceId) {
    if (picasso.shutdown) {
      throw new IllegalStateException(
          "Picasso instance already shut down. Cannot submit new requests.");
    }
    this.picasso = picasso;
    //指向分流程4
    this.data = new Request.Builder(uri, resourceId, picasso.defaultBitmapConfig);
  }

    //分流程4
 Builder(Uri uri, int resourceId, Bitmap.Config bitmapConfig) {
      this.uri = uri;
      this.resourceId = resourceId;
      this.config = bitmapConfig;
    }   

上面代码主要是进行请求的数据构造(如图片的地址,图片的配置信息)。

      public void into(ImageView target) {
        //指向分流程5
        into(target, null);
      }

        //分流程5
    public void into(ImageView target, Callback callback) {
    long started = System.nanoTime();
    //检查当前操作是否在UI线程,如果不在,抛出异常
    checkMain();
    //检查当前要显示的视图控件是否为null
    if (target == null) {
      throw new IllegalArgumentException("Target must not be null.");
    }
    //如果当前的视图控件没有设置图片资源
    if (!data.hasImage()) {
      picasso.cancelRequest(target);
        //如果设置了占位图,加载占位图
      if (setPlaceholder) {
        setPlaceholder(target, getPlaceholderDrawable());
      }
      return;
    }
    //如果当前的RequestCreator对于图片还有配置
    if (deferred) {
        //如果用户已经设置了图片大小(fit属性和resize不可以同时使用)
      if (data.hasSize()) {
        throw new IllegalStateException("Fit cannot be used with resize.");
      }
      int width = target.getWidth();
      int height = target.getHeight();
      if (width == 0 || height == 0) {
        if (setPlaceholder) {
          setPlaceholder(target, getPlaceholderDrawable());
        }
        //该方法最终会向Map<ImageView, DeferredRequestCreator>中进行添加操作
        picasso.defer(target, new DeferredRequestCreator(this, target, callback));
        return;
      }
        //重新设置图片大小
      data.resize(width, height);
    }
    //根据前面的一些配置信息构建出Request对象
    Request request = createRequest(started);
    //根据请求生成一个带有请求配置信息的一个key
    String requestKey = createKey(request);
    //根据缓存策略,如果内存中存在
    if (shouldReadFromMemoryCache(memoryPolicy)) {
        //根据请求的key从内存中获取Bitmap
      Bitmap bitmap = picasso.quickMemoryCacheCheck(requestKey);
      if (bitmap != null) {
        //取消请求
        picasso.cancelRequest(target);
        //设置Bitmap到控件上 指向分流程6
        setBitmap(target, picasso.context, bitmap, MEMORY, noFade, picasso.indicatorsEnabled);
        if (picasso.loggingEnabled) {
          log(OWNER_MAIN, VERB_COMPLETED, request.plainId(), "from " + MEMORY);
        }
        if (callback != null) {
          callback.onSuccess();
        }
        return;
      }
    }
    //如果设置了占位图
    if (setPlaceholder) {
      setPlaceholder(target, getPlaceholderDrawable());
    }

    Action action =
        new ImageViewAction(picasso, target, request, memoryPolicy, networkPolicy, errorResId,
            errorDrawable, requestKey, tag, callback, noFade);
    //指向分流程7
    picasso.enqueueAndSubmit(action);
  } 

//分流程6
static void setBitmap(ImageView target, Context context, Bitmap bitmap,
      Picasso.LoadedFrom loadedFrom, boolean noFade, boolean debugging) {
    Drawable placeholder = target.getDrawable();
   //如果当前的控件有动画,停止播放动画
    if (placeholder instanceof AnimationDrawable) {
      ((AnimationDrawable) placeholder).stop();
    }
    //构建PicassoDrawable对象
    PicassoDrawable drawable =
        new PicassoDrawable(context, bitmap, placeholder, loadedFrom, noFade, debugging);
    target.setImageDrawable(drawable);
  }

//分流程7
  void enqueueAndSubmit(Action action) {
    //获取控件对象
    Object target = action.getTarget();
    if (target != null && targetToAction.get(target) != action) {
      // This will also check we are on the main thread.
      cancelExistingRequest(target);
      targetToAction.put(target, action);
    }
    //指向分流程8
    submit(action);
  } 

    //分流程8
 void submit(Action action) {
    //指向分流程9
    dispatcher.dispatchSubmit(action);
  }

    //分流程9
  void dispatchSubmit(Action action) {
        //通过handler发送一条提交请求的消息 分流程10会进行处理
    handler.sendMessage(handler.obtainMessage(REQUEST_SUBMIT, action));
  }

    //分流程10
    @Override public void handleMessage(final Message msg) {
      switch (msg.what) {
        case REQUEST_SUBMIT: {
            //获取Action
          Action action = (Action) msg.obj;
            //指向分流程11
          dispatcher.performSubmit(action);
          break;
      }


    //分流程11
    void performSubmit(Action action) {
        //指向分流程12
        performSubmit(action, true);
    }

    //分流程12
  void performSubmit(Action action, boolean dismissFailed) {
    if (pausedTags.contains(action.getTag())) {
      pausedActions.put(action.getTarget(), action);
      if (action.getPicasso().loggingEnabled) {
        log(OWNER_DISPATCHER, VERB_PAUSED, action.request.logId(),
            "because tag '" + action.getTag() + "' is paused");
      }
      return;
    }

    BitmapHunter hunter = hunterMap.get(action.getKey());
    if (hunter != null) {
      hunter.attach(action);
      return;
    }

    if (service.isShutdown()) {
      if (action.getPicasso().loggingEnabled) {
        log(OWNER_DISPATCHER, VERB_IGNORED, action.request.logId(), "because shut down");
      }
      return;
    }

    hunter = forRequest(action.getPicasso(), this, cache, stats, action);
    //执行BitmapHunter的run方法 指向分流程13
    hunter.future = service.submit(hunter);
    hunterMap.put(action.getKey(), hunter);
    if (dismissFailed) {
      failedActions.remove(action.getTarget());
    }

    if (action.getPicasso().loggingEnabled) {
      log(OWNER_DISPATCHER, VERB_ENQUEUED, action.request.logId());
    }
  }

BtimapHunter 是一个Runnable 负责解析字节流,生成Bitmap

    //分流程13
  @Override public void run() {
    try {
    //更新线程名字
      updateThreadName(data);
      if (picasso.loggingEnabled) {
        log(OWNER_HUNTER, VERB_EXECUTING, getLogIdsForHunter(this));
      }
    //指向分流程14,该方法本质就是获取一个Bitmap
      result = hunt();
    //根据结果,dispatcure任务调度器进行分发
      if (result == null) {
        dispatcher.dispatchFailed(this);
      } else {
        //内部是通过handler发送一个消息,hanlder是通过Picasso初始化传过来的,下面看一下Picasso类里面handleMessage的处理方法,执行分流程15
        dispatcher.dispatchComplete(this);
      }
    } catch (Downloader.ResponseException e) {
      if (!e.localCacheOnly || e.responseCode != 504) {
        exception = e;
      }
      dispatcher.dispatchFailed(this);
    } catch (NetworkRequestHandler.ContentLengthException e) {
      exception = e;
      dispatcher.dispatchRetry(this);
    } catch (IOException e) {
      exception = e;
      dispatcher.dispatchRetry(this);
    } catch (OutOfMemoryError e) {
      StringWriter writer = new StringWriter();
      stats.createSnapshot().dump(new PrintWriter(writer));
      exception = new RuntimeException(writer.toString(), e);
      dispatcher.dispatchFailed(this);
    } catch (Exception e) {
      exception = e;
      dispatcher.dispatchFailed(this);
    } finally {
      Thread.currentThread().setName(Utils.THREAD_IDLE_NAME);
    }
  }

    //分流程14
    Bitmap hunt() throws IOException {
        Bitmap bitmap = null;
        //根据缓存策略,如果从缓存中读取
        if (shouldReadFromMemoryCache(memoryPolicy)) {
            //根据key找出内存中的bitmap
          bitmap = cache.get(key);
          if (bitmap != null) {
            stats.dispatchCacheHit();
            loadedFrom = MEMORY;
            if (picasso.loggingEnabled) {
              log(OWNER_HUNTER, VERB_DECODED, data.logId(), "from cache");
            }
            return bitmap;
          }
        }
    //----下面是请求网络,获取bitmap
        data.networkPolicy = retryCount == 0 ? NetworkPolicy.OFFLINE.index : networkPolicy;
        RequestHandler.Result result = requestHandler.load(data, networkPolicy);
        if (result != null) {
          loadedFrom = result.getLoadedFrom();
          exifRotation = result.getExifOrientation();

          bitmap = result.getBitmap();

         //判断如果bitmap为null,通过流的方式进行强转bitmap
          if (bitmap == null) {
            InputStream is = result.getStream();
            try {
              bitmap = decodeStream(is, data);
            } finally {
              Utils.closeQuietly(is);
            }
          }
        }

        //下方主要是根据图片的一些配置信息,进行相应的处理,最终返回bitmap
        if (bitmap != null) {
          if (picasso.loggingEnabled) {
            log(OWNER_HUNTER, VERB_DECODED, data.logId());
          }
          stats.dispatchBitmapDecoded(bitmap);
          if (data.needsTransformation() || exifRotation != 0) {
            synchronized (DECODE_LOCK) {
              if (data.needsMatrixTransform() || exifRotation != 0) {
                bitmap = transformResult(data, bitmap, exifRotation);
                if (picasso.loggingEnabled) {
                  log(OWNER_HUNTER, VERB_TRANSFORMED, data.logId());
                }
              }
              if (data.hasCustomTransformations()) {
                bitmap = applyCustomTransformations(data.transformations, bitmap);
                if (picasso.loggingEnabled) {
                  log(OWNER_HUNTER, VERB_TRANSFORMED, data.logId(), "from custom transformations");
                }
              }
            }
            if (bitmap != null) {
              stats.dispatchBitmapTransformed(bitmap);
            }
          }
        }

        return bitmap;
      } 
    //分流程15
    static final Handler HANDLER = new Handler(Looper.getMainLooper()) {
    @Override public void handleMessage(Message msg) {
      switch (msg.what) {
        //处理图片加载完成的逻辑
        case HUNTER_BATCH_COMPLETE: {
          @SuppressWarnings("unchecked") List<BitmapHunter> batch = (List<BitmapHunter>) msg.obj;
          //noinspection ForLoopReplaceableByForEach
          for (int i = 0, n = batch.size(); i < n; i++) {
            BitmapHunter hunter = batch.get(i);
            //指向分流程16
            hunter.picasso.complete(hunter);
          }
          break;
        }
        case REQUEST_GCED: {
          Action action = (Action) msg.obj;
          if (action.getPicasso().loggingEnabled) {
            log(OWNER_MAIN, VERB_CANCELED, action.request.logId(), "target got garbage collected");
          }
          action.picasso.cancelExistingRequest(action.getTarget());
          break;
        }
        case REQUEST_BATCH_RESUME:
          @SuppressWarnings("unchecked") List<Action> batch = (List<Action>) msg.obj;
          //noinspection ForLoopReplaceableByForEach
          for (int i = 0, n = batch.size(); i < n; i++) {
            Action action = batch.get(i);
            action.picasso.resumeAction(action);
          }
          break;
        default:
          throw new AssertionError("Unknown handler message received: " + msg.what);
      }
    }
  };
    //分流程16
  void complete(BitmapHunter hunter) {
    Action single = hunter.getAction();
    List<Action> joined = hunter.getActions();

    boolean hasMultiple = joined != null && !joined.isEmpty();
    boolean shouldDeliver = single != null || hasMultiple;

    if (!shouldDeliver) {
      return;
    }

    Uri uri = hunter.getData().uri;
    Exception exception = hunter.getException();
    //获取Bitmap对象从BitmapHunter中
    Bitmap result = hunter.getResult();
    LoadedFrom from = hunter.getLoadedFrom();

    if (single != null) {
      deliverAction(result, from, single);
    }

    if (hasMultiple) {
      //noinspection ForLoopReplaceableByForEach
      for (int i = 0, n = joined.size(); i < n; i++) {
        Action join = joined.get(i);
        //进行Action里面的方法分发 指向分流程17
        deliverAction(result, from, join);
      }
    }

    if (listener != null && exception != null) {
      listener.onImageLoadFailed(this, uri, exception);
    }
  }
    //分流程17
    private void deliverAction(Bitmap result, LoadedFrom from, Action action) {
    if (action.isCancelled()) {
      return;
    }
    if (!action.willReplay()) {
      targetToAction.remove(action.getTarget());
    }
    if (result != null) {
      if (from == null) {
        throw new AssertionError("LoadedFrom cannot be null.");
      }
    //回调complete接口 指向分流程18
      action.complete(result, from);
      if (loggingEnabled) {
        log(OWNER_MAIN, VERB_COMPLETED, action.request.logId(), "from " + from);
      }
    } else {
    //回调error接口 
      action.error();
      if (loggingEnabled) {
        log(OWNER_MAIN, VERB_ERRORED, action.request.logId());
      }
    }
  }
    //分流程18
@Override public void complete(Bitmap result, Picasso.LoadedFrom from) {
    if (result == null) {
      throw new AssertionError(
          String.format("Attempted to complete action with no result!\n%s", this));
    }
    //获取目标控件
    ImageView target = this.target.get();
    if (target == null) {
      return;
    }

    Context context = picasso.context;
    boolean indicatorsEnabled = picasso.indicatorsEnabled;
    //执行分流程19
    PicassoDrawable.setBitmap(target, context, result, from, noFade, indicatorsEnabled);

    if (callback != null) {
      callback.onSuccess();
    }
  }
    //分流程19

  static void setBitmap(ImageView target, Context context, Bitmap bitmap,
      Picasso.LoadedFrom loadedFrom, boolean noFade, boolean debugging) {
    Drawable placeholder = target.getDrawable();
    if (placeholder instanceof AnimationDrawable) {
      ((AnimationDrawable) placeholder).stop();
    }
    //创建PicassoDrawable对象
    PicassoDrawable drawable =
        new PicassoDrawable(context, bitmap, placeholder, loadedFrom, noFade, debugging);
    //加载drawable到控件上
    target.setImageDrawable(drawable);
  }

以上主要是讲解了一下Picasso框架加载图片的一个整体的流程,可以说逻辑比较清晰,相信大家完全可以理解Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView)这段代码背后所隐藏的秘密。

总结:通过上面的代码分析,相信大家会对Picasso框架有个基本的认识和体会,下面我总结一下Picasso框架的一个基本流程,先构建出一个Request对象,然后通过Dispatcher进行分发,最终执行操作处理的是XXXHandler,然后BtimapHunter负责解析字节流到Bitmap,任务调度器Dispatcher对结果进行分发,通过Dispatcher内部的hanlder进行通信,最终会回调到Action的回调方法中进行相关的成功或者失败处理。这边文章主要是基本的源码理解,下一篇文章我会带来Picasso的实战操作!

你可能感兴趣的:(Android框架,Picasso框架,图片框架)