Picasso优先级策略
请求的优先级
public enum Priority {
LOW, // 只有当通过fetch方法(不需要ImageView,仅需要下载Bitmap并执行回调)请求图片时才会给request设置该优先级
NORMAL,// 正常的请求优先级
HIGH//
}
图片下载任务的优先级
真实的项目开发过程中,只请求图片而不设置给ImageView毕竟是少数,所以大多数的任务依然会是NORMAL级别的,同级别的任务数太多,那么优先级策略就没有太大的效果,所以,Picasso在执行图片下载任务时,又做了第二次优先级划分
1. 依赖于优先级队列的线程池
PicassoExecutorService() {
super(DEFAULT_THREAD_COUNT, DEFAULT_THREAD_COUNT, 0, TimeUnit.MILLISECONDS,
new PriorityBlockingQueue<Runnable>(), new Utils.PicassoThreadFactory());
}
2. 实现了Comparable接口的FutureTask
private static final class PicassoFutureTask extends FutureTask<BitmapHunter>
implements Comparable<PicassoFutureTask> {
private final BitmapHunter hunter;
public PicassoFutureTask(BitmapHunter hunter) {
super(hunter, null);
this.hunter = hunter;
}
@Override
public int compareTo(PicassoFutureTask other) {
Picasso.Priority p1 = hunter.getPriority();
Picasso.Priority p2 = other.hunter.getPriority();
//高优先级的请求放到队列前面
//同等级的请求按照顺序先后执行
return (p1 == p2 ? hunter.sequence - other.hunter.sequence :
p2.ordinal() - p1.ordinal());
}
}
PicassoExecutorService(Picasso自己封装的线程池,对移动网络做了处理,并提供了支持优先级比较的FutureTask)
//这段代码我们在将来的开发中可能会用得上,包含了国内每种移动网络
switch (info.getType()) {
case ConnectivityManager.TYPE_WIFI:
case ConnectivityManager.TYPE_WIMAX:
case ConnectivityManager.TYPE_ETHERNET:
setThreadCount(4);
break;
case ConnectivityManager.TYPE_MOBILE:
switch (info.getSubtype()) {
case TelephonyManager.NETWORK_TYPE_LTE: // 4G
case TelephonyManager.NETWORK_TYPE_HSPAP:
case TelephonyManager.NETWORK_TYPE_EHRPD:
setThreadCount(3);
break;
case TelephonyManager.NETWORK_TYPE_UMTS: // 3G
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_EVDO_B:
setThreadCount(2);
break;
case TelephonyManager.NETWORK_TYPE_GPRS: // 2G
case TelephonyManager.NETWORK_TYPE_EDGE:
setThreadCount(1);
break;
default:
setThreadCount(DEFAULT_THREAD_COUNT);
}
break;
default:
setThreadCount(DEFAULT_THREAD_COUNT);
}
} |