android - 构建 Volley Singleton 的正确方法

标签 android android-volley

编辑:“重复问题”没有提供此问题的适用答案。那里提供的方法并不能消除两个警告,只能消除一个。另外,我的问题包含第二部分,该部分也没有得到解答。

如果我按照官方教程构建一个Volley Singleton,

https://developer.android.com/training/volley/requestqueue.html#singleton

我收到警告

private static VolleySingleton mInstance 

private static Context mContext 

说“不要将 android 上下文类放置在静态字段中”。我已经阅读了有关此问题的其他 Stackoverflow 问题,但我发现没有解决方案可以消除此警告,也没有找到真正解释这里发生的情况的答案。 是的,我读过这篇文章: Warning: Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run) 但我无法提取出适用的答案。我实际上需要更改什么才能不破坏即时运行或泄漏某些内容?

我不明白的另一件事是,为什么我必须使用 <T>

public <T> void addToRequestQueue(Request <T> request)

我知道这代表泛型,但如果我删除它们,它仍然有效。那么它存在的原因是什么?

这是我的 Volley Singleton,请有人建议我正确构建它,而不会出现警告和冗余:

public class VolleySingleton {
private static VolleySingleton mInstance;
private static Context mContext;
private RequestQueue mRequestQueue;

private VolleySingleton(Context context) {
    mContext = context;
    mRequestQueue = getRequestQueue();
}

public static synchronized VolleySingleton getInstance(Context context) {
    if (mInstance == null) {
        mInstance = new VolleySingleton(context);
    }

    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
    }

    return mRequestQueue;
}

public <T> void addToRequestQueue(Request <T> request) {
    getRequestQueue().add(request);
}
}

最佳答案

需要明确的是,这是一个重复的。我遵循了评论中链接的问题中提出的建议,并设法编写了您需要的类,而在 Android Studio 上没有任何 lint 警告。这是一个 fragment :

public class VolleySingleton {

  private static VolleySingleton instance;
  private RequestQueue requestQueue;

  private VolleySingleton(Context context) {
    requestQueue = Volley.newRequestQueue(context.getApplicationContext());
  }

  public static VolleySingleton getInstance(Context context) {
    if (instance == null) {
      instance = new VolleySingleton(context);
    }
    return  instance;
  }

  public RequestQueue getRequestQueue(){
    return requestQueue;
  }
}

关于android - 构建 Volley Singleton 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47941438/

相关文章:

android - 如何传递包含对象列表的可打包对象?

Android Google Map V2 身份验证问题

android - Adapter.notifyDataSetChanged() 不工作

android - 是否可以在 android 操作系统上运行简单的 python 游戏

c# - 如何将 post 请求从 Android 发送到 C# web API

android - 如何通过带有 header 的 volley 发布 JSON 请求?

java - Volley JsonObjectRequest 发布请求忽略参数

android - 如何自定义android AlertDialog文本属性

Android Volley 库 : do we always have to repeat Response. Listener 和 Response.ErrorListener

android - 检查 Volley 是从缓存还是通过网络获取结果