- 自动的调度网络请求
- 多并发的网络请求
- 可以缓存http请求
- 支持请求的优先级
- 支持取消请求的API,可以取消单个请求,可以设置取消请求的范围域。
- 代码标准化,使开发者更容易专注于我们的业务的逻辑处理
- 更容易给UI填充来自网络请求的数据
- Volley可以是作为调试和跟踪的工具
lolafon 2015-04-18
Volley从服务器端请求字符串数据,图片数据,和JSON格式数据。Volley可以写出标准化的模板代码,并让我们更加关注于我们的业务逻辑,这对于我们的App来说是非常重要的。
Volley的优势:
Volley非常不适合大的文件流操作,例如上传和下载。因为Volley会把所有的服务器端返回的数据在解析期间缓存进内存。大量的下载操作可以考虑用DownLoaderManager和异步加载来实现。
Volley库的地址如下:
git clone https://android.googlesource.com/platform/frameworks/volley
Volley提供了一个便利的方法Volley.newRequestQueue可以使用默认的设置创建一个RequestQueue,例如:
finalTextView mTextView =(TextView) findViewById(R.id.text); ... // Instantiate the RequestQueue. RequestQueue queue =Volley.newRequestQueue(this); String url ="http://www.google.com"; // Request a string response from the provided URL. StringRequest stringRequest =newStringRequest(Request.Method.GET, url, newResponse.Listener<String>(){ @Override publicvoid onResponse(String response){ // Display the first 500 characters of the response string. mTextView.setText("Response is: "+ response.substring(0,500)); } },newResponse.ErrorListener(){ @Override publicvoid onErrorResponse(VolleyError error){ mTextView.setText("That didn't work!"); } }); // Add the request to the RequestQueue. queue.add(stringRequest);
<code style="font-family:Consolas, 'Liberation Mono', Menlo, Courier, monospace;" class="language-java">
publicclassMainActivityextendsActivity{ privateImageView mImageView; @Override protectedvoid onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mImageView =(ImageView) findViewById(R.id.iv_image); } publicvoid requestImage(){ // Retrieves an image specified by the URL, displays it in the UI. String url ="http://i.imgur.com/7spzG.png"; ImageRequest request =newImageRequest(url, newResponse.Listener<Bitmap>(){ @Override publicvoid onResponse(Bitmap bitmap){ Toast.makeText(MainActivity.this,"success",1).show(); mImageView.setImageBitmap(bitmap); } },0,0,null,newResponse.ErrorListener(){ publicvoid onErrorResponse(VolleyError error){ /*mImageView .setImageResource(R.drawable.image_load_error);*/ } }); Volley.newRequestQueue(getApplicationContext()).add(request); } }
<code style="font-family:Consolas, 'Liberation Mono', Menlo, Courier, monospace;" class="language-java">
<com.android.volley.toolbox.NetworkImageView android:id="@+id/networkImageView" android:layout_width="150dp" android:layout_height="170dp" android:layout_centerHorizontal="true"/>
<code style="font-family:Consolas, 'Liberation Mono', Menlo, Courier, monospace;" class="language-java">
ImageLoader mImageLoader; ImageView mImageView; // The URL for the image that is being loaded. private static final String IMAGE_URL = "http://developer.android.com/images/training/system-ui.png"; ... mImageView = (ImageView) findViewById(R.id.regularImageView); // Get the ImageLoader through your singleton class. mImageLoader = MySingleton.getInstance(this).getImageLoader(); mImageLoader.get(IMAGE_URL, ImageLoader.getImageListener(mImageView,R.drawable.def_image, R.drawable.err_image));
TextView mTxtDisplay; ImageView mImageView; mTxtDisplay = (TextView) findViewById(R.id.txtDisplay); String url = "http://my-json-feed"; JsonObjectRequest jsObjRequest = new JsonObjectRequest (Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { mTxtDisplay.setText("Response: " + response.toString()); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // TODO Auto-generated method stub } }); // Access the RequestQueue through your singleton class. MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);
TextView mTxtDisplay; ImageView mImageView; mTxtDisplay = (TextView) findViewById(R.id.txtDisplay); String url = "http://my-json-feed"; JsonObjectRequest jsObjRequest = new JsonObjectRequest (Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { mTxtDisplay.setText("Response: " + response.toString()); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // TODO Auto-generated method stub } }); // Access the RequestQueue through your singleton class. MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);
给请求设置TAG,并放进请求队列
public static final String TAG = "MyTag"; StringRequest stringRequest; // Assume this exists. RequestQueue mRequestQueue; // Assume this exists. // 给请求设置tag stringRequest.setTag(TAG); // 把请求放进请求队列 mRequestQueue.add(stringRequest);
在onstop方法中取消所有设置Tag的请求
@Override protected void onStop () { super.onStop(); if (mRequestQueue != null) { mRequestQueue.cancelAll(TAG); } }
注意:当取消请求的时候,onResponse和onErrorResponse方法将不会执行
RequestQueue mRequestQueue; // 配置缓存大小 Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap // 设置网络请求方式(UrlConnection和HttpClient) Network network = new BasicNetwork(new HurlStack()); //初始化RequestQueue mRequestQueue = new RequestQueue(cache, network); // 开启RequestQueue mRequestQueue.start(); String url ="http://www.myurl.com"; // Formulate the request and handle the response. StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { // Do something with the response } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // Handle error } }); // 把请求添加进请求队列 mRequestQueue.add(stringRequest);5.2 RequestQueue中BasicNewWork(网络)的内部机制
HttpStack stack; ... // If the device is running a version >= Gingerbread... if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { // ...use HttpURLConnection for stack. } else { // ...use AndroidHttpClient for stack. } Network network = new BasicNetwork(stack);
private static MySingleton mInstance; private RequestQueue mRequestQueue; private static Context mCtx; 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; } }