picasso源码简单解析


只分析最常用的使用方式Picasso.with(MainActivity.this).load(uri).into(img);
这里只分析该语句涉及的部分,至于图形变换等其他操作不分析。

 

public static Picasso with(Context context) {
  if (singleton == null) {
    synchronized (Picasso.class) {
      if (singleton == null) {
        singleton = new Builder(context).build();//
      }
    }
  }
  return singleton;
}

 

可以看到with返回的实际上是一个单例Picasso对象,该对象是通过Builder类的build函数生成的,先看Builder类的构造函数:

/** Start building a new {@link Picasso} instance. */
public Builder(Context context) {
  if (context == null) {
    throw new IllegalArgumentException("Context must not be null.");
  }
  this.context = context.getApplicationContext();
}

builder的构造函数里把context对象转化成了ApplicationContext,该对象在程序的整个生命周期都有效,这点和glide不同,glide还要处理不同contex的生命周期。得到Builder对象之后调用build():

 

/** Builder.build. */
  public Picasso build() {
    Context context = this.context;
    
/*图片下载器,可以选择okhttp或者模块内置的下载器*/
    if (downloader == null) {
      downloader = Utils.createDefaultDownloader(context);
    }
    if (cache == null) {
      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);
  }
}

 

在这里对Picasso的参数进行了设置,重点关注dispacher,非常重要,后面会分析。Picasso.with生成单例之后调用load函数加载图片资源:

 

public RequestCreator load(Uri uri) {
  return new RequestCreator(this, uri, 0);
}

with返回了Picasso实例之后调用load函数,这里以uri为例子(string类型的参数会转化成uri),实际返回了一个RequestCreator,我们看看它的构造函数:

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;
  this.data = new Request.Builder(uri, resourceId, picasso.defaultBitmapConfig);
}

 

这里的data对象很重要,里面会存储uri和resourceId,继续走,load之后实际产生的是一个RequestCreator对象,接着调用该对象的into方法

public void into(ImageView target, Callback callback) {
  long started = System.nanoTime();
  checkMain();/*保证在主线程中执行,这点需要关注*/
  
/*这段函数比较长,去掉了中间的一些非强相关函数以便分析*/
  Request request = createRequest(started);
  String requestKey = createKey(request);
  
/*缓存在这里也不分析,去掉*/
  
  Action action =
      new ImageViewAction(picasso, target, request, memoryPolicy, networkPolicy, errorResId,
          errorDrawable, requestKey, tag, callback, noFade);

  picasso.enqueueAndSubmit(action);
}
 
 

 

这里的request比较重要,里面的内容是用之前提到的data生成的,里面存的数据也包含我们需要关注uri和resourceId,之后生成了requestkey主要用来做缓存的。然后看action,包含了所有需要处理的信息,我们重点关注request和target两个参数。一个Action就是把request获得的bitmap放入target中,是之前所有调用过程的浓缩。看这个action是如何处理的:

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

 

void submit(Action action) {
  dispatcher.dispatchSubmit(action);
}

 

void dispatchSubmit(Action action) {
  handler.sendMessage(handler.obtainMessage(REQUEST_SUBMIT, action));
}

 

直到这里,发现调用的是dispatcher的handler,发送了REQUEST_SUBMIT这消息待处理。我们回到之前dispatcher生成的时候,看构造函数

Dispatcher(Context context, ExecutorService service, Handler mainThreadHandler,
    Downloader downloader, Cache cache, Stats stats) {
  this.dispatcherThread = new DispatcherThread();
  this.dispatcherThread.start();
  Utils.flushStackLocalLeaks(dispatcherThread.getLooper());
  this.context = context;
  this.service = service;
  this.hunterMap = new LinkedHashMap<String, BitmapHunter>();
  this.failedActions = new WeakHashMap<Object, Action>();
  this.pausedActions = new WeakHashMap<Object, Action>();
  this.pausedTags = new HashSet<Object>();
  this.handler = new DispatcherHandler(dispatcherThread.getLooper(), this);
  this.downloader = downloader;
  this.mainThreadHandler = mainThreadHandler;
  this.cache = cache;
  this.stats = stats;
  this.batch = new ArrayList<BitmapHunter>(4);
  this.airplaneMode = Utils.isAirplaneModeOn(this.context);
  this.scansNetworkChanges = hasPermission(context, Manifest.permission.ACCESS_NETWORK_STATE);
  this.receiver = new NetworkBroadcastReceiver(this);
  receiver.register();
}

可以看到dispatcher里包含一个dispatcherThread线程,handler发送的消息由该线程处理,构成了一个消息循环。由于调用的是sendMessage函数,处理函数在handler里面:

private static class DispatcherHandler extends Handler {
  private final Dispatcher dispatcher;

  public DispatcherHandler(Looper looper, Dispatcher dispatcher) {
    super(looper);
    this.dispatcher = dispatcher;
  }

  @Override public void handleMessage(final Message msg) {
    switch (msg.what) {
      case REQUEST_SUBMIT: {
        Action action = (Action) msg.obj;
        dispatcher.performSubmit(action);
        break;
      }
      case REQUEST_CANCEL: {
        Action action = (Action) msg.obj;
        dispatcher.performCancel(action);
        break;
      }
      case TAG_PAUSE: {
        Object tag = msg.obj;
        dispatcher.performPauseTag(tag);
        break;
      }
      case TAG_RESUME: {
        Object tag = msg.obj;
        dispatcher.performResumeTag(tag);
        break;
      }
      case HUNTER_COMPLETE: {
        BitmapHunter hunter = (BitmapHunter) msg.obj;
        dispatcher.performComplete(hunter);
        break;
      }
      case HUNTER_RETRY: {
        BitmapHunter hunter = (BitmapHunter) msg.obj;
        dispatcher.performRetry(hunter);
        break;
      }
      case HUNTER_DECODE_FAILED: {
        BitmapHunter hunter = (BitmapHunter) msg.obj;
        dispatcher.performError(hunter, false);
        break;
      }
      case HUNTER_DELAY_NEXT_BATCH: {
        dispatcher.performBatchComplete();
        break;
      }
      case NETWORK_STATE_CHANGE: {
        NetworkInfo info = (NetworkInfo) msg.obj;
        dispatcher.performNetworkStateChange(info);
        break;
      }
      case AIRPLANE_MODE_CHANGE: {
        dispatcher.performAirplaneModeChange(msg.arg1 == AIRPLANE_MODE_ON);
        break;
      }
      default:
        Picasso.HANDLER.post(new Runnable() {
          @Override public void run() {
            throw new AssertionError("Unknown handler message received: " + msg.what);
          }
        });
    }
  }
}

 

关注handlemessag这个函数,看对应REQUEST_SUBMIT的处理逻辑,在第一个处理

case REQUEST_SUBMIT: {
        Action action = (Action) msg.obj;
        dispatcher.performSubmit(action);
        break;
      }

我们看看performSubmit:

void performSubmit(Action action) {
  performSubmit(action, true);
}

 

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

重点关注

hunter= forRequest(action.getPicasso(), this,cache, stats, action);
 hunter.future = service.submit(hunter);

这两行,第一行生成一个hunter,在里面主要是选择requesthandler,第二行调用了service的submit函数。我们知道service是一个线程池,传进去的hunter最终会调用hunter的run函数,再看看hunter的run函数

@Override public void run() {
  try {
    updateThreadName(data);

    if (picasso.loggingEnabled) {
      log(OWNER_HUNTER, VERB_EXECUTING, getLogIdsForHunter(this));
    }

    result = hunt();

    if (result == null) {
      dispatcher.dispatchFailed(this);
    } else {
      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);
  }
}
这里run函数的代码是在线程池里进行的,要注意。run调用了hunt函数,hunt函数实现了处理request请求,转化成bitmap存在hunter中。得到结果之后,调用了dispatcher.dispatchComplete(this);走进去:
void dispatchComplete(BitmapHunter hunter) {
  handler.sendMessage(handler.obtainMessage(HUNTER_COMPLETE, hunter));
}

 

到这里把hunter对象发到dispatchcer thread中处理,完成了一次线程空间切换,走进dispatcherhandler,看HUNTER_COMPLETE对应的处理流程:

case HUNTER_COMPLETE: {
  BitmapHunter hunter = (BitmapHunter) msg.obj;
  dispatcher.performComplete(hunter);
  break;
}

 

看performComplete

void performComplete(BitmapHunter hunter) {
  if (shouldWriteToMemoryCache(hunter.getMemoryPolicy())) {
    cache.set(hunter.getKey(), hunter.getResult());
  }
  hunterMap.remove(hunter.getKey());
  batch(hunter);
  if (hunter.getPicasso().loggingEnabled) {
    log(OWNER_DISPATCHER, VERB_BATCHED, getLogIdsForHunter(hunter), "for completion");
  }
}

 

private void batch(BitmapHunter hunter) {
  if (hunter.isCancelled()) {
    return;
  }
  batch.add(hunter);
  if (!handler.hasMessages(HUNTER_DELAY_NEXT_BATCH)) {
    handler.sendEmptyMessageDelayed(HUNTER_DELAY_NEXT_BATCH, BATCH_DELAY);
  }
}

 

可以看到dispatcherThread将HUNTER_DELAY_NEXT_BATCH,消息发到自己的消息队列,看处理逻辑

case HUNTER_DELAY_NEXT_BATCH: {
  dispatcher.performBatchComplete();
  break;
}

 

void performBatchComplete() {
  List<BitmapHunter> copy = new ArrayList<BitmapHunter>(batch);
  batch.clear();
  mainThreadHandler.sendMessage(mainThreadHandler.obtainMessage(HUNTER_BATCH_COMPLETE, copy));
  logBatch(copy);
}

 

在这里调用了mainHandler进行处理,这里的mainHandler实际上就是Picasso类里的HANDLER静态变量,这个handler初始化时传入的主线程的looper,因此里面的处理函数是在主线程进行的。

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

可以看到对应消息的处理,调用的是picasso的complete函数对hunter进行处理。注意这里是在主线程处理的:

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 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);
      deliverAction(result, from, join);
    }
  }

  if (listener != null && exception != null) {
    listener.onImageLoadFailed(this, uri, exception);
  }
}

这里调用了deliverAction对结果进行处理,看deliverAction源码:

 

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.");
    }
    action.complete(result, from);
    if (loggingEnabled) {
      log(OWNER_MAIN, VERB_COMPLETED, action.request.logId(), "from " + from);
    }
  } else {
    action.error();
    if (loggingEnabled) {
      log(OWNER_MAIN, VERB_ERRORED, action.request.logId());
    }
  }
}

 

 

最终调用了action的complete方法,我们发现是一个抽象方法,因此要看这个action最初是什么类型,往前翻发现最初是在into函数里定义的,是ImageViewAction,看ImageViewAction得comoplete代码:

@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;
  PicassoDrawable.setBitmap(target, context, result, from, noFade, indicatorsEnabled);

  if (callback != null) {
    callback.onSuccess();
  }
}

 

我们看到终于将bitmap设置到target里了。到这里整个分析完成,关于网络下载的过程没有具体分析,如果要分析的话主要代码一个是在NetworkRequestHandler的load函数里,一个是在hunter的hunt函数里,读者可以依据需求自行分析
 
总结一下整个过程

Picasso.with(MainActivity.this).load(uri).into(img);

经历了 主线程->dispatcher线程->线程池子线程->dispatcher线程->主线程 的线程空间切换的过程,特别要注意,调用into函数必须在主线程进行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值