Android 网络通信框架Volley简介

Volley是2013年Google I/O上发布的,它是Android平台上的网络通信库,对常用的网络通信功能作了封装,能使网络通信更快,更简单,更健壮。以前使用网络通信一般都是用AsyncTaskLoader、HttpURLConnection、AsyncTask等。

Volley适合数据量小但通信频繁的情况下

Volley架构

下图就是Google I/O 演讲时使用的图片

技术分享

主要分主线程、Cache线程、Network线程,从图中说明可以看出,主线程、Cache线程都只有一个,而NetworkDispatcher线程可以有多个,整个架构是以线程池作为基础。Volley的主要作用:
1、获取JSON对象
2、图片加载

使用Volley的好处:
1、Volley automatically schedule all network requests. It means that Volley will be taking care of all the network requests your app executes for fetching response or image from web.
2、Volley provides transparent disk and memory caching.
3、Volley provides powerful cancellation request API. It means that you can cancel a single request or you can set blocks or scopes of requests to cancel.
4、Volley provides powerful customization abilities.
5、Volley provides Debugging and tracing tools
Volley的使用
首先要得到Volley的源码或jar包
Volley的git地址:https://android.googlesource.com/platform/frameworks/volley
安装了git后可以通过以下命令得到它的源码:

git clone https://android.googlesource.com/platform/frameworks/volley
在Ubuntu12.04终端上使用如下命令可以得到最新的volley源码,然后在源码环境下编译出jar包

dzt@uu:~/Volley$ git clone https://android.googlesource.com/platform/frameworks/volley
Cloning into 'volley'...
remote: Counting objects: 52, done
remote: Finding sources: 100% (52/52)
remote: Total 2851 (delta 259), reused 2851 (delta 259)
Receiving objects: 100% (2851/2851), 1.13 MiB | 369 KiB/s, done.
Resolving deltas: 100% (259/259), done.
使用源码编译Volley模块

dzt@uu:~/dzt/android_source_4.4$ mmm /home/dzt/GioneeApp/Volley/volley/
============================================
PLATFORM_VERSION_CODENAME=REL
PLATFORM_VERSION=4.4.2
TARGET_PRODUCT=aosp_arm
TARGET_BUILD_VARIANT=eng
TARGET_BUILD_TYPE=release
TARGET_BUILD_APPS=
TARGET_ARCH=arm
TARGET_ARCH_VARIANT=armv7-a
TARGET_CPU_VARIANT=generic
HOST_ARCH=x86
HOST_OS=linux
HOST_OS_EXTRA=Linux-3.11.0-26-generic-x86_64-with-Ubuntu-12.04-precise
HOST_BUILD_TYPE=release
BUILD_ID=KOT49H
OUT_DIR=out
============================================
make:进入目录'/home/dzt/dzt/android_source_4.4'
target Java: volley (out/target/common/obj/JAVA_LIBRARIES/volley_intermediates/classes)
注意:/home/dzt/GioneeApp/Volley/volley/src/main/java/com/android/volley/RequestQueue.java 使用了未经检查或不安全
的操作。
注意:要了解详细信息,请使用 -Xlint:unchecked 重新编译。
Copying: out/target/common/obj/JAVA_LIBRARIES/volley_intermediates/classes-jarjar.jar
Copying: out/target/common/obj/JAVA_LIBRARIES/volley_intermediates/emma_out/lib/classes-jarjar.jar
Copying: out/target/common/obj/JAVA_LIBRARIES/volley_intermediates/classes.jar
target Static Jar: volley (out/target/common/obj/JAVA_LIBRARIES/volley_intermediates/javalib.jar)
make:离开目录“/home/dzt/dzt/android_source_4.4”
dzt@uu:~/dzt/android_source_4.4$ 
会生成一个Static Jar包,路径:out/target/common/obj/JAVA_LIBRARIES/volley_intermediates/javalib.jar

Volley的源码与jar包可以到这下载:http://download.csdn.net/detail/deng0zhaotai/8581201

Volley的简单应用

技术分享
打印Json数据

04-10 15:50:54.932 D/Volley_dzt( 6005): JsonRequest------POST------{"weatherinfo":{"weather6":"小雨转阴","weather5":"小雨","weather4":"阴转小雨","index_d":"建议着薄外套、开衫牛仔衫裤等服装。年老体弱者应适当添加衣物,宜着夹克衫、
薄毛衣等。","city":"深圳","img_single":"1","index_cl":"适宜","img2":"99","img1":"1","index":"较舒适","tempF1":"68℉~59℉","img_title10":"小雨","img_title11":"小雨","img_title12":"阴","index_xc":"不宜","index_co":"舒
适","img_title_single":"多云","date_y":"2014年3月4日","city_en":"shenzhen","index48_d":"建议着薄外套、开衫牛仔衫裤等服装。年老体弱者应适当添加衣物,宜着夹克衫、薄毛衣
等。","img9":"7","img7":"2","img8":"7","img5":"7","img6":"99","img3":"7","img4":"99","fx1":"微风","st5":"21","st6":"14","st3":"21","date":"","st4":"15","st1":"20","st2":"15","temp1":"20℃~15℃","tempF6":"66.2℉
~57.2℉","temp2":"20℃~15℃","temp3":"21℃~16℃","index48":"较舒适","tempF4":"66.2℉~60.8℉","tempF5":"68℉~59℉","index_ls":"适宜","tempF2":"68℉~59℉","tempF3":"69.8℉~60.8℉","index_tr":"适宜","index_ag":"极易
发","index48_uv":"最弱","fl1":"小于3级","fl5":"小于3级","fl4":"小于3级","temp6":"19℃~14℃","fl3":"3-4级","temp5":"20℃~15℃","fl2":"小于3级","temp4":"19℃~16℃","cityid":"101280601","img_title7":"阴","img12":"2","img_title6":"小
雨","fl6":"小于3级","img_title5":"小雨","img_title4":"小雨","fchh":"11","img_title9":"小雨","img10":"99","img_title8":"小雨","img11":"7","fx2":"微风","wind1":"微风","weather1":"多云","wind3":"东风3-4级","weather2":"小
雨","wind2":"微风","weather3":"小雨","wind5":"微风","img_title3":"小雨","index_uv":"弱","wind4":"微风","img_title2":"多云","img_title1":"多云","wind6":"微风","week":"星期二"}}
参考代码

package com.dzt.volleydemo;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.util.LruCache;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.ImageView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageCache;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

public class MainActivity extends ActionBarActivity {

	private static final String TAG = "Volley_dzt";
	private static final String URL = "http://www.baidu.com";
	private static final String WEATHER_URL = "http://m.weather.com.cn/data/101280601.html";
	private static final String PICTURE1 = "http://img05.tooopen.com/images/20150407/tooopen_sy_84397424841.jpg";
	private static final String PICTURE2 = "http://img1.3lian.com/img2008/06/019/cn32.jpg";

	private RequestQueue mQueue;
	private ImageView mImageView;
	private NetworkImageView mNetworkImageView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mQueue = Volley.newRequestQueue(getApplicationContext());
		RequestGet();
		Log.i(TAG, "---------------------------------------------------1");
		RequestPost();
		Log.i(TAG, "---------------------------------------------------2");
		JsonRequest();
		getJsonRequest();
		postJsonRequest();
		Log.i(TAG, "---------------------------------------------------3");
		initWidget();
		loadImageByVolley();
		showImageByNetworkImageView();
	}

	private void initWidget() {
		mImageView = (ImageView) findViewById(R.id.imageView);
		mNetworkImageView = (NetworkImageView) findViewById(R.id.networkImageView);
	}

	/**
	 * 利用NetworkImageView显示网络图片
	 */
	private void showImageByNetworkImageView() {
		final LruCache<String, Bitmap> lruCache = new LruCache<String, Bitmap>(
				20);
		ImageCache imageCache = new ImageCache() {
			@Override
			public void putBitmap(String key, Bitmap value) {
				Log.i(TAG,
						"showImageByNetworkImageView-------------------putBitmap");
				lruCache.put(key, value);
			}

			@Override
			public Bitmap getBitmap(String key) {
				Log.i(TAG,
						"showImageByNetworkImageView-------------------getBitmap");
				return lruCache.get(key);
			}
		};
		ImageLoader imageLoader = new ImageLoader(mQueue, imageCache);
		mNetworkImageView.setTag("url");
		mNetworkImageView.setImageUrl(PICTURE1, imageLoader);
	}

	/**
	 * 利用Volley异步加载图片
	 * 
	 */
	private void loadImageByVolley() {
		final LruCache<String, Bitmap> lruCache = new LruCache<String, Bitmap>(
				20);
		ImageCache imageCache = new ImageCache() {
			@Override
			public void putBitmap(String key, Bitmap value) {
				Log.i(TAG, "loadImageByVolley-------------------putBitmap");
				lruCache.put(key, value);
			}

			@Override
			public Bitmap getBitmap(String key) {
				Log.i(TAG, "loadImageByVolley-------------------getBitmap");
				return lruCache.get(key);
			}
		};
		ImageLoader imageLoader = new ImageLoader(mQueue, imageCache);
		// 注意getImageListener参数
		ImageListener listener = ImageLoader.getImageListener(mImageView,
				R.drawable.ic_launcher, R.drawable.error);
		imageLoader.get(PICTURE2, listener);
	}

	private void RequestGet() {
		StringRequest stringRequest = new StringRequest(URL,
				new Response.Listener<String>() {
					@Override
					public void onResponse(String response) {
						Log.d(TAG, "RequestGet----------" + response);
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						Log.e(TAG, error.getMessage(), error);
					}
				});
		mQueue.add(stringRequest);
	}

	private void RequestPost() {
		StringRequest stringRequest = new StringRequest(Method.POST, URL,
				new Response.Listener<String>() {
					@Override
					public void onResponse(String response) {
						Log.d(TAG, "RequestPost----------" + response);
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						Log.e(TAG, error.getMessage(), error);
					}
				}) {
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				// TODO Auto-generated method stub
				Map<String, String> map = new HashMap<String, String>();
				map.put("params1", "value1");
				map.put("params2", "value2");
				return map;
			}
		};
		mQueue.add(stringRequest);
	}

	/**
	 * 利用Volley获取JSON数据
	 */
	private void JsonRequest() {
		// 显示进度条
		final ProgressDialog progressDialog = ProgressDialog.show(this,
				"This is title", "...Loading...");
		JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
				WEATHER_URL, null, new Response.Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject response) {
						Log.d(TAG,
								"JsonRequest------------" + response.toString());
						// 加载完成后取消进度条
						if (progressDialog.isShowing()
								&& progressDialog != null) {
							progressDialog.dismiss();
						}
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						Log.e(TAG, error.getMessage(), error);
					}
				});
		mQueue.add(jsonObjectRequest);
	}

	/**
	 * 利用Volley GET请求获取JSON数据
	 */
	private void getJsonRequest() {
		JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Method.GET,
				WEATHER_URL, null, new Response.Listener<JSONObject>() {
					@Override
					public void onResponse(JSONObject response) {
						Log.d(TAG,
								"JsonRequest-----GET-------"
										+ response.toString());
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						Log.e(TAG, error.getMessage(), error);
					}
				});
		mQueue.add(jsonObjectRequest);
	}

	/**
	 * 利用Volley POST请求获取JSON数据
	 */
	private void postJsonRequest() {
		JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
				Method.POST, WEATHER_URL, null,
				new Response.Listener<JSONObject>() {
					@Override
					public void onResponse(JSONObject response) {
						Log.d(TAG,
								"JsonRequest------POST------"
										+ response.toString());
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						Log.e(TAG, error.getMessage(), error);
					}
				});
		mQueue.add(jsonObjectRequest);
	}
}
布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.dzt.volleydemo.MainActivity" >

    <com.android.volley.toolbox.NetworkImageView
        android:id="@+id/networkImageView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginTop="10dp"
        android:layout_weight="1" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

</LinearLayout>

Demo程序:http://download.csdn.net/detail/deng0zhaotai/8581755

还有一种可以获取一张图片的方法

	private void RequestImage() {
		ImageRequest imgRequest = new ImageRequest(PICTURE1,
				new Response.Listener<Bitmap>() {
					@Override
					public void onResponse(Bitmap arg0) {
						// TODO Auto-generated method stub
						mSingleView.setImageBitmap(arg0);
					}
				}, 300, 200, Config.ARGB_8888, new ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError arg0) {
						// TODO Auto-generated method stub

					}
				});
		mQueue.add(imgRequest);
	}
也可以取消请求

@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		mQueue.cancelAll(this);

	}
最新的下载:http://download.csdn.net/detail/deng0zhaotai/8582101

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。