Code For Better Google Developer Voice - Volley Library in Android

Volley is an HTTP library that makes networking for Android applications very easy and fast. It was developed by Google and launched during Google I/O 2013. It was developed because of the lack of networking classes in the Android SDK that would work without compromising the user experience. Although Volley is part of the Android Open Source Project (AOSP), Google announced in January 2017 that Volley would be migrated to a separate library. It manages the handling and caching of network requests and saves developers valuable time writing the same network call/caching code over and over again. Volley is not suitable for large downloads or streaming operations because Volley keeps all responses in memory during parsing.

Features of Volley

1. Request queuing and prioritization
2. Efficient request caching and memory management
3. Library scalability and customization to meet our needs
4. Cancellation of requests

Advantages of using Volley

1. All tasks that need to be done using Networking in Android can be done with the help of Volley.
2. Automatic scheduling of network requests.
3. Capture.
4. Multiple concurrent network connections.
5. Cancel request API.
6. Request priority.
7. Volley provides debugging and tracing tools.

How to import Volley and add permissions

Before you start using Volley, you need to import Volley and add permissions in your Android project. The steps to do so are as follows:

Create a new project . Open build.gradle(Module: app) and add the following dependencies:

dependencies{
    
     
    //...
    implementation 'com.android.volley:volley:1.0.0'
}

After AndroidManifest.xmladding internet permissions:

<uses-permission android:name="android.permission.INTERNET" />

Categories in Volley Library

Volley has two main categories:

1. Request Queue : Interest used when distributing requests to the network. You can create a request queue if you want, but usually it's created early on at startup, and you keep it and use it as a Singleton.
2. Request : All the necessary information to make a Web API call is stored in it. It is the basis for creating network requests (GET, POST).

Request types using the Volley library

string request

String url = "https:// string_url/";
StringRequest
	stringRequest
	= new StringRequest(
		Request.Method.GET,
		url,
		new Response.Listener() {
    
    
			@Override
			public void onResponse(String response)
			{
    
    
			}
		},
		new Response.ErrorListener() {
    
    
			@Override
			public void onErrorResponse(VolleyError error)
			{
    
    
			}
		});
requestQueue.add(stringRequest);
</pre>

JSON object request

String url = "https:// json_url/";
JsonObjectRequest
	jsonObjectRequest
	= new JsonObjectRequest(
		Request.Method.GET,
		url,
		null,
		new Response.Listener() {
    
    
			@Override
			public void onResponse(JSONObject response)
			{
    
    
			}
		},
		new Response.ErrorListener() {
    
    
			@Override
			public void onErrorResponse(VolleyError error)
			{
    
    
			}
		});
requestQueue.add(jsonObjectRequest);

JSONArray request

JsonArrayRequest
	jsonArrayRequest
	= new JsonArrayRequest(
		Request.Method.GET,
		url,
		null,
		new Response.Listener() {
    
    
			@Override
			public void onResponse(JSONArray response)
			{
    
    
			}
		},
		new Response.ErrorListener() {
    
    
			@Override
			public void onErrorResponse(VolleyError error)
			{
    
    
			}
		});
requestQueue.add(jsonArrayRequest);

image request

int max - width = ...;
int max_height = ...;

String URL = "http:// image_url.png";

ImageRequest
	imageRequest
	= new ImageRequest(URL,
					new Response.Listener() {
    
    
						@Override
						public void
						onResponse(Bitmap response)
						{
    
    
							// Assign the response
							// to an ImageView
							ImageView
								imageView
								= (ImageView)
									findViewById(
										R.id.imageView);

							imageView.setImageBitmap(response);
						}
					},
					max_width, max_height, null);

requestQueue.add(imageRequest);

Add post parameters

String tag_json_obj = "json_obj_req";

String
	url
	= "https:// api.xyz.info/volley/person_object.json";

ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...PLease wait");
pDialog.show();

JsonObjectRequest
	jsonObjReq
	= new JsonObjectRequest(
		Method.POST,
		url,
		null,
		new Response.Listener() {
    
    

			@Override
			public void onResponse(JSONObject response)
			{
    
    
				Log.d(TAG, response.toString());
				pDialog.hide();
			}
		},
		new Response.ErrorListener() {
    
    

			@Override
			public void onErrorResponse(VolleyError error)
			{
    
    
				VolleyLog.d(TAG, "Error: "
									+ error.getMessage());
				pDialog.hide();
			}
		}) {
    
    

		@Override
		protected Map getParams()
		{
    
    
			Map params = new HashMap();
			params.put("name", "Androidhive");
			params.put("email", "[email protected]");
			params.put("password", "password123");

			return params;
		}

	};

AppController.getInstance()
	.addToRequestQueue(jsonObjReq, tag_json_obj);

Add request header

String tag_json_obj = "json_obj_req";

String
	url
	= "https:// api.androidhive.info/volley/person_object.json";

ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();

JsonObjectRequest
	jsonObjReq
	= new JsonObjectRequest(
		Method.POST,
		url,
		null,
		new Response.Listener() {
    
    

			@Override
			public void onResponse(JSONObject response)
			{
    
    
				Log.d(TAG, response.toString());
				pDialog.hide();
			}
		},
		new Response.ErrorListener() {
    
    

			@Override
			public void onErrorResponse(VolleyError error)
			{
    
    
				VolleyLog.d(TAG, "Error: "
									+ error.getMessage());
				pDialog.hide();
			}
		}) {
    
    

		@Override
		public Map getHeaders() throws AuthFailureError
		{
    
    
			HashMap headers = new HashMap();
			headers.put("Content-Type", "application/json");
			headers.put("apiKey", "xxxxxxxxxxxxxxx");
			return headers;
		}

	};

AppController.getInstance()
	.addToRequestQueue(jsonObjReq, tag_json_obj);

Handle Volley cache

// 从缓存加载请求
Cache
	cache
	= AppController.getInstance()
		.getRequestQueue()
		.getCache();

Entry entry = cache.get(url);
if (entry != null) {
    
    
	try {
    
    
		String
			data
			= new String(entry.data, "UTF-8");
		// 处理数据,例如将其转换为 xml、json、位图等,
	}
	catch (UnsupportedEncodingException e) {
    
    
		e.printStackTrace();
	}
}
}
else
{
    
    
	// 如果缓存的响应不存在
}

// 使缓存无效
AppController.getInstance()
	.getRequestQueue()
	.getCache()
	.invalidate(url, true);

// 关闭缓存字符串请求
StringRequest
	stringReq
	= new StringRequest(....);

// 禁用缓存
stringReq.setShouldCache(false);

// 删除特定缓存的缓存</strong>
AppController.getInstance()
	.getRequestQueue()
	.getCache()
	.remove(url);

// 删除所有缓存
AppController.getInstance()
	.getRequestQueue()
	.getCache()
	.clear(url);

cancel request

// 取消单个请求
String tag_json_arry = "json_req";

ApplicationController.getInstance()
	.getRequestQueue()
	.cancelAll("feed_request");

// 取消所有请求
ApplicationController.getInstance()
	.getRequestQueue()
	.cancelAll();

request priority

private Priority priority = Priority.HIGH;

StringRequest
	strReq
	= new StringRequest(
		Method.GET,
		Const.URL_STRING_REQ,
		new Response
			.Listener() {
    
    

					@Override
					public void onResponse(String response) {
    
    

						Log.d(TAG, response.toString());
						msgResponse.setText(response.toString());
						hideProgressDialog();

					} },
		new Response
			.ErrorListener() {
    
    

					@Override
					public void
					onErrorResponse(VolleyError error) {
    
    

						VolleyLog.d(TAG,
									"Error: "
										+ error.getMessage());
						hideProgressDialog();
					} }) {
    
    

		@Override
		public Priority getPriority()
		{
    
    
			return priority;
		}

	};

Guess you like

Origin blog.csdn.net/qq_53544522/article/details/126774617