Use newRequestQueue和发送Request

使用RequestQueue并向其中传递Request对象可以.RequestQueue管理和网络操作相关的一些线程,b

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
mTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);

取消一个Request

可以使用cacel方法取消一个Request,防止其总是在连接网络.

所以常在onStop()方法中调用cancel相关方法.

1
2
3
4
5
6
7
8
9
ublic static final String TAG = "MyTag";
StringRequest stringRequest; // Assume this exists.
RequestQueue mRequestQueue; // Assume this exists.

// Set the tag on the request.
stringRequest.setTag(TAG);

// Add the request to the RequestQueue.
mRequestQueue.add(stringRequest);
1
2
3
4
5
6
7
@Override
protected void onStop () {
super.onStop();
if (mRequestQueue != null) {
mRequestQueue.cancelAll(TAG);
}
}