android - Volley, ImageLoader.ImageListener 中的 onResponse 调用了多少次

标签 android android-intent android-volley

我‘使用 Volley 进行互联网请求。我认为 onResponse 方法应该在收到响应时只调用一次,但我发现它调用了两次。

这是我的代码:

YVolley.getInstance(context).getImageLoader().get(category.child.get(i).icon, new ImageLoader.ImageListener() {
                @Override
                public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
                    Drawable drawable = new BitmapDrawable(context.getResources(), response.getBitmap());
                    drawable.setBounds(0, 0, GeneralUtil.dip2px(context, 45), GeneralUtil.dip2px(context, 45));
                    button.setCompoundDrawables(null, drawable, null, null);
                    Log.i("swifter", "get icon ... success == "+url);
                }

                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.i("swifter", "get drawable icon error...");
                }
            });

“成功”日志打印了两次。

是我的代码有问题还是应该是这样的?

最佳答案

我在 the documentation for ImageLoader.java 中找到了答案.文档指出:

The call flow is this:

  1. Upon being attached to a request, onResponse(response, true) will be invoked to reflect any cached data that was already available. If the data was available, response.getBitmap() will be non-null.

  2. After a network response returns, only one of the following cases will happen:

    • onResponse(response, false) will be called if the image was loaded, or
    • onErrorResponse will be called if there was an error loading the image.

基于此,存在三种可能的响应模式。我已经在示例应用程序中测试并确认了这些。

图像从缓存中加载的

在这种情况下会有一个调用:

  • onRespsonse(response, true) 将被调用,您可以从 response.getBitmap() 获取图像。

图像不是从缓存加载,从网络加载

在这种情况下会有两个调用:

  • 首先,将调用 onRespsonse(response, true),并且 response.getBitmap() 将为 null

  • 然后,onRespsonse(response, false) 将被调用,您可以从 response.getBitmap() 获取图像。

图像不是从缓存加载的,也不是从网络加载的

在这种情况下会有两个调用:

  • 首先,将调用 onRespsonse(response, true),并且 response.getBitmap() 将为 null

  • 然后,onErrorResponse(error) 会被调用,错误的详细信息可以从 error 中找到(这将是 的一个实例VolleyError).


在您的情况下,以下代码 fragment 将帮助您跳过第一个“空”响应:

@Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
    // skip cache failure
    if (isImmediate && response.getBitmap() == null) return;

    // ...
}

希望这有助于弄清楚为什么您的请求可能会收到两个响应。

关于android - Volley, ImageLoader.ImageListener 中的 onResponse 调用了多少次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32216704/

相关文章:

java - 如何使用 Volley 库从 android studio 调用 WooCommerce API?

java - Android Volley 同步请求不起作用

android - 如何在打包文件时使用 Gradle 删除原始 XML 文件中的注释

android - 获取 android 模拟器的 udid

android - 您可以从 ActionBar 的下拉导航中启动 Activity Intent 吗

android - 完成 Activity/Intent

java - 如何在 Android 中使用带有 if-else 语句的 boolean 值显示我的 TextView?

android - 如何在托管多个 fragment 的选项卡式 Activity 中进行多个 HTTP 调用?

android - 想完全关闭应用程序

使用名称值对的 Android Volley 发布请求