android 图片加载框架 之 Picasso

1.Picasso介绍
Picasso开源地址:https://github.com/square/picasso
Picasso是Square公司开源的一个Android平台上的图片加载框架,简单易用,可以实现图片下载和缓存功能。
2.Picasso的使用方法
(1)gradle的配置

    compile 'com.squareup.picasso:picasso:2.5.2'  

(2)普通图片加载方式
path 为加载目标(图片)地址

    Picasso.with(context).load("path").into(imageView);  

(3)转换图片以适应布局大小并减少内存占用

    Picasso.with(context)  
     .load(url)  
     .resize(50, 50)  
     .centerCrop()  
     .into(imageView);  

(4)进行展示空白或者错误占位图片

Picasso.with(context)  
  .load(url)  
  .placeholder(R.drawable.placeholder_null)  
  .error(R.drawable.placeholder_error)  
.into(imageView); 

(5)其他各种不同资源的加载方式

Picasso.with(context).load(R.drawable.landing_screen).into(imageview);  
Picasso.with(context).load(new File(...)).into(imageview);  
Picasso.with(context).load("file:///android_asset/ic_uncher.png").into(imageview); 

3.流程与原理的分析

//主流程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对象

//分流程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);
  }

原理的分析参考一篇博客,博客的路径是:http://blog.csdn.net/a1002450926/article/details/50430019
希望大家一起学习。

猜你喜欢

转载自blog.csdn.net/lamboo_cn/article/details/52261235