文章摘要
1恃锉、volley 網(wǎng)絡請求隊列和緩沖請求隊列
2、volley 單例模式
一螃成、設定網(wǎng)絡請求隊列和緩沖請求隊列
RequestQueue需要兩件事來做它的工作:
- 一個網(wǎng)絡來執(zhí)行請求的傳輸
- 一個緩存來處理緩存旦签。
在Volley toolbox中有這些可用的標準實現(xiàn):DiskBasedCache為每一個文件提供了具有內(nèi)存索引的響應緩存查坪,BasicNetwork根據(jù)您首選的HTTP客戶端提供網(wǎng)絡傳輸。
BasicNetwork是Volley的默認網(wǎng)絡實現(xiàn)宁炫,BasicNetwork必須使用HTTP client來完成初始化偿曙,通常是HttpURLConnection。
此代碼段顯示了設置RequestQueue所涉及的步驟:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView mTextView = (TextView) findViewById(R.id.text);
RequestQueue mRequestQueue;
// Instantiate the cache 1羔巢、初始化Cache
Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
// Set up the network to use HttpURLConnection as the HTTP client.
//2望忆、建立網(wǎng)絡連接
Network network = new BasicNetwork(new HurlStack());
// Instantiate the RequestQueue with the cache and network.
//3、構建初始化RequestQueue
mRequestQueue = new RequestQueue(cache, network);
// Start the queue
//4竿秆、啟動RequestQueue
mRequestQueue.start();
String url = "http://www.example.com";
// Formulate the request and handle the response.
//5启摄、初始化并構建Request
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Do something with the response
mTextView.setText("Response is: " + response.substring(0, 500));
Log.d("hlwang","CreateRequestQueue onResponse response is:"+response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Handle error
Log.d("hlwang","CreateRequestQueue onErrorResponse error is:"+error);
}
});
// Add the request to the RequestQueue.
//6、將Request加入隊列
mRequestQueue.add(stringRequest);
}
如果您只需要一次性請求幽钢,并且不想離開線程池歉备,則可以在需要的地方創(chuàng)建RequestQueue,并在響應或錯誤返回后調(diào)用stop Queue匪燕,就像“在發(fā)送簡單請求”中提到的Volley.newRequestQueue()方法蕾羊。
但是更常見的用例是將RequestQueue創(chuàng)建為單例模式對象,以保持其在應用程序生命周期中運行:
二帽驯、使用Singleton模式
如果您的應用程序不斷使用網(wǎng)絡龟再,可能最有效的方法是設置一個可以延長應用程序生命周期的RequestQueue實例。
要達到這種目標界拦,有各種方式可以實現(xiàn)吸申。 推薦的方法是實現(xiàn)封裝RequestQueue和其他Volley功能的單例類梗劫。 另一種方法是在Application.onCreate()中繼承Application并設置RequestQueue享甸, 但這種做法是不鼓勵的, 靜態(tài)單例可以以更模塊化的方式提供相同的功能梳侨。
一個關鍵的概念是RequestQueue必須用Application context而不是Activity context來實例化蛉威。 這樣可以確保RequestQueue在您的應用程序生命周期中持續(xù)存在,而不是每次重新創(chuàng)建Activity時重新創(chuàng)建(例如走哺,當用戶旋轉(zhuǎn)設備時)蚯嫌。
下面是一個提供RequestQueue和ImageLoader功能的單例類的例子:
package hailouwang.demosforapi.volley;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.LruCache;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
/**
* Created by ifei on 2017/7/26.
*/
public class MySingleton {
private static MySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
private MySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
@Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized MySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new MySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
return mImageLoader;
}
}
下面是執(zhí)行的一些例子RequestQueue使用單例類的操作:
// Get a RequestQueue
RequestQueue queue = MySingleton.getInstance(this.getApplicationContext()).
getRequestQueue();
// ...
// Add a request (in this example, called stringRequest) to your RequestQueue.
MySingleton.getInstance(this).addToRequestQueue(stringRequest);