通过前面的谈话,我相信你有Volley有了一定的了解了原理。本章将给出一些我们的应用程序都可以在样品中直接使用,第一样品是

NetworkImageView类,事实上NetworkImageView顾名思义就是将异步的操作封装在了控件本身,这样的设计能够充分保留控件的移植性和维护性。

NetworkImageView通过调用setImageUrl来指定详细的url:

public void setImageUrl(String url, ImageLoader imageLoader) {
mUrl = url;
mImageLoader = imageLoader;
// The URL has potentially changed. See if we need to load it.
loadImageIfNecessary(false);
}
void loadImageIfNecessary(final boolean isInLayoutPass) {
int width = getWidth();
int height = getHeight(); boolean wrapWidth = false, wrapHeight = false;
if (getLayoutParams() != null) {
wrapWidth = getLayoutParams().width == LayoutParams.WRAP_CONTENT;
wrapHeight = getLayoutParams().height == LayoutParams.WRAP_CONTENT;
} // if the view's bounds aren't known yet, and this is not a wrap-content/wrap-content
// view, hold off on loading the image.
boolean isFullyWrapContent = wrapWidth && wrapHeight;
if (width == 0 && height == 0 && !isFullyWrapContent) {
return;
} // if the URL to be loaded in this view is empty, cancel any old requests and clear the
// currently loaded image.
if (TextUtils.isEmpty(mUrl)) {
if (mImageContainer != null) {
mImageContainer.cancelRequest();
mImageContainer = null;
}
setDefaultImageOrNull();
return;
} // if there was an old request in this view, check if it needs to be canceled.
if (mImageContainer != null && mImageContainer.getRequestUrl() != null) {
if (mImageContainer.getRequestUrl().equals(mUrl)) {
// if the request is from the same URL, return.
return;
} else {
// if there is a pre-existing request, cancel it if it's fetching a different URL.
mImageContainer.cancelRequest();
setDefaultImageOrNull();
}
} // Calculate the max image width / height to use while ignoring WRAP_CONTENT dimens.
int maxWidth = wrapWidth ? 0 : width;
int maxHeight = wrapHeight ? 0 : height; // The pre-existing content of this view didn't match the current URL. Load the new image
// from the network.
ImageContainer newContainer = mImageLoader.get(mUrl,
new ImageListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (mErrorImageId != 0) {
setImageResource(mErrorImageId);
}
} @Override
public void onResponse(final ImageContainer response, boolean isImmediate) {
// If this was an immediate response that was delivered inside of a layout
// pass do not set the image immediately as it will trigger a requestLayout
// inside of a layout. Instead, defer setting the image by posting back to
// the main thread.
if (isImmediate && isInLayoutPass) {
post(new Runnable() {
@Override
public void run() {
onResponse(response, false);
}
});
return;
} if (response.getBitmap() != null) {
setImageBitmap(response.getBitmap());
} else if (mDefaultImageId != 0) {
setImageResource(mDefaultImageId);
}
}
}, maxWidth, maxHeight); // update the ImageContainer to be the new bitmap container.
mImageContainer = newContainer;
}

我们从这段逻辑不难看出,url这个属性的持有者是ImageContainer.当Bitmap相应的url与Container相应的url同样的时候,Volley将直接返回。

否则将通过一个叫做ImageLoader的对象get.

ImageContainer newContainer = mImageLoader.get(mUrl,
new ImageListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (mErrorImageId != 0) {
setImageResource(mErrorImageId);
}
} @Override
public void onResponse(final ImageContainer response, boolean isImmediate) {
// If this was an immediate response that was delivered inside of a layout
// pass do not set the image immediately as it will trigger a requestLayout
// inside of a layout. Instead, defer setting the image by posting back to
// the main thread.
if (isImmediate && isInLayoutPass) {
post(new Runnable() {
@Override
public void run() {
onResponse(response, false);
}
});
return;
} if (response.getBitmap() != null) {
setImageBitmap(response.getBitmap());
} else if (mDefaultImageId != 0) {
setImageResource(mDefaultImageId);
}
}
}, maxWidth, maxHeight);

ImageLoader.get(String requestUrl, ImageListener imageListener,

            int maxWidth, int maxHeight):

public ImageContainer get(String requestUrl, ImageListener imageListener,
int maxWidth, int maxHeight) {
// only fulfill requests that were initiated from the main thread.
throwIfNotOnMainThread(); final String cacheKey = getCacheKey(requestUrl, maxWidth, maxHeight); // Try to look up the request in the cache of remote images.
Bitmap cachedBitmap = mCache.getBitmap(cacheKey);
if (cachedBitmap != null) {
// Return the cached bitmap.
ImageContainer container = new ImageContainer(cachedBitmap, requestUrl, null, null);
imageListener.onResponse(container, true);
return container;
} // The bitmap did not exist in the cache, fetch it!
ImageContainer imageContainer =
new ImageContainer(null, requestUrl, cacheKey, imageListener); // Update the caller to let them know that they should use the default bitmap.
imageListener.onResponse(imageContainer, true); // Check to see if a request is already in-flight.
BatchedImageRequest request = mInFlightRequests.get(cacheKey);
if (request != null) {
// If it is, add this request to the list of listeners.
request.addContainer(imageContainer);
return imageContainer;
} // The request is not already in flight. Send the new request to the network and
// track it.
Request<?> newRequest =
new ImageRequest(requestUrl, new Listener<Bitmap>() {
<span style="color:#009900;">@Override
public void onResponse(Bitmap response) {
onGetImageSuccess(cacheKey, response);
}</span>
}, maxWidth, maxHeight,
Config.RGB_565, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
onGetImageError(cacheKey, error);
}
}); mRequestQueue.add(newRequest);
mInFlightRequests.put(cacheKey,
new BatchedImageRequest(newRequest, imageContainer));
return imageContainer;
}

ImageLoader開始的第一步你可能非常难理解,为什么须要自己从Cache中获得?RequestQueue不是都已经帮你做好了这些么?实际上这个Cache是NetworkImageView 自己定义的Cache:ImageCache。而这样的Cache被Volley抛给用户去实现,你能够通过适配器模式装饰成为你自己的Cache,也能够装饰成DiskBaseCache。

通过绿色段代码我们能够知道当ImageLoader在Volley返回的时候回调 onGetImageSuccess(cacheKey, response)方法。

这种方法是为了补充回调ImageLoader自定义的ImageListener回调

private void batchResponse(String cacheKey, BatchedImageRequest request) {
mBatchedResponses.put(cacheKey, request);
// If we don't already have a batch delivery runnable in flight, make a new one.
// Note that this will be used to deliver responses to all callers in mBatchedResponses.
if (mRunnable == null) {
mRunnable = new Runnable() {
@Override
public void run() {
for (BatchedImageRequest bir : mBatchedResponses.values()) {
for (ImageContainer container : bir.mContainers) {
// If one of the callers in the batched request canceled the request
// after the response was received but before it was delivered,
// skip them.
if (container.mListener == null) {
continue;
}
if (bir.getError() == null) {
container.mBitmap = bir.mResponseBitmap;
container.mListener.onResponse(container, false);
} else {
container.mListener.onErrorResponse(bir.getError());
}
}
}
mBatchedResponses.clear();
mRunnable = null;
} };
// Post the runnable.
mHandler.postDelayed(mRunnable, mBatchResponseDelayMs);
}
}

能够看到,这一切的命令都发生在UI线程中。最后通过ImageListener回调来实现图片设置。

public static ImageListener getImageListener(final ImageView view,
final int defaultImageResId, final int errorImageResId) {
return new ImageListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (errorImageResId != 0) {
view.setImageResource(errorImageResId);
}
} @Override
public void onResponse(ImageContainer response, boolean isImmediate) {
if (response.getBitmap() != null) {
view.setImageBitmap(response.getBitmap());
} else if (defaultImageResId != 0) {
view.setImageResource(defaultImageResId);
}
}
};
}

版权声明:本文博客原创文章。博客,未经同意,不得转载。

[Android]Volley源代码分析(店)应用的更多相关文章

  1. [Android] Volley源代码分析(五岁以下儿童)Q \\ u0026一个

    Volley源代码分析系列那里一段时间,告诉我,有许多私人留言,同时一些问题抛出.对于一些简单的问题,我们跳,这两天被连接到朋友@smali提出的问题.告诉我你不得不赞叹查看源代码时的详细程度,大家一 ...

  2. [Android]Volley源代码分析(二)Cache

    Cache作为Volley最为核心的一部分,Volley花了重彩来实现它.本章我们顺着Volley的源代码思路往下,来看下Volley对Cache的处理逻辑. 我们回忆一下昨天的简单代码,我们的入口是 ...

  3. [Android]Volley源代码分析(叁)Network

    假设各位看官细致看过我之前的文章,实际上Network这块的仅仅是点小功能的补充.我们来看下NetworkDispatcher的核心处理逻辑: <span style="font-si ...

  4. Android HttpURLConnection源代码分析

    Android HttpURLConnection源代码分析 之前写过HttpURLConnection与HttpClient的差别及选择.后来又分析了Volley的源代码. 近期又遇到了问题,想在V ...

  5. Android 消息处理源代码分析(1)

    Android 消息处理源代码分析(1) 在Android中,通常被使用的消息队列的代码在文件夹\sources\android-22\android\os下,涉及到下面几个类文件 Handler.j ...

  6. Android HandlerThread 源代码分析

    HandlerThread 简单介绍: 我们知道Thread线程是一次性消费品,当Thread线程运行完一个耗时的任务之后.线程就会被自己主动销毁了.假设此时我又有一 个耗时任务须要运行,我们不得不又 ...

  7. Android KLog源代码分析

    Android KLog源代码分析 Android KLog源代码分析 代码结构 详细分析 BaseLog FileLog JsonLog XmlLog 核心文件KLogjava分析 遇到的问题 一直 ...

  8. android开发源代码分析--多个activity调用多个jni库的方法

    android开发源代码分析--多个activity调用多个jni库的方法 有时候,我们在开发android项目时会遇到须要调用多个native c/jni库文件,下面是本人以前实现过的方法,假设有知 ...

  9. Android 消息处理源代码分析(2)

    Android 消息处理源代码分析(1)点击打开链接 继续接着分析剩下的类文件 Looper.java public final class Looper { final MessageQueue m ...

随机推荐

  1. 在Android开发中,定时器一般有以下3种实现方法

    在Android开发中,定时器一般有以下3种实现方法: 原文地址http://www.360doc.com/content/12/0619/13/87000_219180978.shtml 一.采用H ...

  2. mysql 监控 大批量的插入,删除,和修改

    监控大批量的插入,修改和删除: mysql> insert into aaa select * from aaa; mysql> SELECT trx_id, trx_state, trx ...

  3. highcharts dynamic change line color

    mouseOut: function(){ this.series.graph.attr({"stroke","#ccc"}) }

  4. UF访问,一些对用友最新的旗舰级产品U9一些引进(图像)

    昨天,北京用友公司的本地UF马平之和几个同事总和.并且e创客网站访问者创始人江.双方进行了友好的交流.首先,我们公司的历史.销售.或产品介绍. 然后.用友分公司的总水平介绍了用友的情况下,,马总介绍了 ...

  5. 分享最新15个加速 Web 开发的框架和工具(梦想天空)

    我们为开发人员挑选了15个最新的  Web 开发框架,你肯定尝试一下这些新鲜的框架,有的可能略微复杂,有的提供了很多的配置选项,也有一些窗口小部件和界面交互的选择.他们将帮助你创建更优秀的网站,提供给 ...

  6. 查询mysql哪些表正在被锁状态

    1.查进程,主要是查找被锁表的那个进程的ID SHOW PROCESSLIST; 2.kill掉锁表的进程ID KILL   10866;//后面的数字即时进程的ID

  7. 11.ThinkPHP 3.1.2 连贯操作

    ==================================================== 一.常用连贯操作 1.where 帮助我们设置查询条件 2.order 对结果进行排序 $ar ...

  8. 在SharePoint 2013 中使用文档库Scheduling (计划公布功能)

    本文讲述在SharePoint2013 中使用文档库Scheduling (计划公布功能)的步骤和注意的事项. 文档库Scheduling (计划公布功能) 用于设定当文档通过审批后特定的时间区间内才 ...

  9. 体验魅力Cognos BI 10 系列,第1 部分: 第一次安装

    体验魅力Cognos BI 10 系列,第1 部分: 第一次安装吴敏达, 信息管理软件高级技术顾问, IBM简介: 本系列教程旨在帮助您通过实际动手掌握Cognos BI 10.1 的主要功能.在这一 ...

  10. asp.net2.0安全性(2)--用户个性化设置(2)--转载来自车老师

    上一篇我们用Profile.age等方式可以读取用户的年龄和其它的信息,但有的时候我们要查询显示所有用户的信息,但asp.net没有提供查询所有用户信息的功能,我们只能对现有的用户逐一查询其Profi ...