在我看来,如果您的项目使用Google的volley作为模块(而非jar文件),则可以按照以下方式自定义其类:
选项#1:
第一个文件,RequestQueue.java:
添加一个类变量private boolean mCacheUsed = true;
以及以下构造函数:
public RequestQueue(Cache cache, Network network, int threadPoolSize,
ResponseDelivery delivery, boolean cacheUsed) {
mCache = cache;
mNetwork = network;
mDispatchers = new NetworkDispatcher[threadPoolSize];
mDelivery = delivery;
mCacheUsed = cacheUsed;
}
public RequestQueue(Cache cache, Network network, int threadPoolSize, boolean cacheUsed) {
this(cache, network, threadPoolSize,
new ExecutorDelivery(new Handler(Looper.getMainLooper())), cacheUsed);
}
public RequestQueue(Cache cache, Network network, boolean cacheUsed) {
this(cache, network, DEFAULT_NETWORK_THREAD_POOL_SIZE, cacheUsed);
}
然后,在 public <T> Request<T> add(Request<T> request) {
中,你需要检查如下内容:
if (!request.shouldCache() || !mCacheUsed) {
mNetworkQueue.add(request);
return request;
}
第二个文件,Volley.java:
public static RequestQueue newRequestQueue(Context context, HttpStack stack, boolean cacheUsed) {
File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
String userAgent = "volley/0";
try {
String packageName = context.getPackageName();
PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
userAgent = packageName + "/" + info.versionCode;
} catch (NameNotFoundException e) {
}
if (stack == null) {
if (Build.VERSION.SDK_INT >= 9) {
stack = new HurlStack();
} else {
stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
}
}
Network network = new BasicNetwork(stack);
RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network, cacheUsed);
queue.start();
return queue;
}
public static RequestQueue newRequestQueue(Context context, boolean cacheUsed) {
return newRequestQueue(context, null, cacheUsed);
}
最后,在MainActivity中,例如:
如果想使用可用的缓存:
RequestQueue requestQueue = Volley.newRequestQueue(this, true)
如果不想使用可用的缓存:
RequestQueue requestQueue = Volley.newRequestQueue(this, false)
选项 #2:
Request.java:
新增一个类变量 public boolean mSkipAvailableCache = false;
RequestQueue.java:
在方法 public <T> Request<T> add(Request<T> request)
内,你需要进行以下检查:
if (!request.shouldCache() || request.mSkipAvailableCache) {
mNetworkQueue.add(request);
return request;
}
MainActivity.java: 您可以设置
jsonArrayRequest.mSkipAvailableCache = true
可用的缓存将不会被使用。
希望这可以帮到您!
setShouldCache(bool)
的方法吗?我有一个通用的 Volley 类,所以所有片段都使用相同的添加请求方法。这样一来,我将不得不严重更改逻辑(200多个位置)。 - sandalone