什么是Volley(了解)
Volley是Ficus Kirpatrick在Google I/O 2013发布的一个处理和缓存网络请求的库,能使网络通信更快,更简单,更健壮。Volley名称的由来: a burst or emission of many things or a large amount at once。在Google IO的演讲上,其配图是一幅发射火弓箭的图,有点类似流星。见下图
Volley用来做什么(了解)
发送Request请求(文字信息的处理)
图片下载的处理
VolleyUtils
public class VolleyUtils {
private static VolleyUtils instance;
public RequestQueue getQueue() {
return mQueue;
}
private RequestQueue mQueue;
private VolleyUtils(Context context) {
//TODO do sth
mQueue = Volley.newRequestQueue(context);
}
//双层判空的单例模式
public static VolleyUtils getInstance(Context context) {
if (instance == null) {
synchronized (VolleyUtils.class) {
if (instance == null) {
instance = new VolleyUtils(context);
}
}
}
return instance;
}
public void getData(int method, String url, Response.Listener<String> listener, Response.ErrorListener errorListener) {
StringRequest request = new StringRequest(method, url, listener, errorListener);
mQueue.add(request);
}
}
MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn_str;
private TextView tv_result;
private Button btn_net;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_str = (Button) findViewById(R.id.btn_str);
btn_net = (Button) findViewById(R.id.btn_net);
tv_result = (TextView) findViewById(R.id.tv_result);
btn_str.setOnClickListener(this);
btn_net.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_str:
//TODO 字符串的网络请求
//1. 创建请求队列 RequestQueue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//2. 创建请求对象
//p1: 请求方式 p2: 请求的url p3:请求成功的接口的回调 p4:请求失败的接口的回调
StringRequest strReq = new StringRequest(Request.Method.GET, Constant.URL_NET
, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
TestBean testBean = new Gson().fromJson(response, TestBean.class);
//回调结果在主线程,可以直接更新UI
tv_result.setText(testBean.data.WallpaperListInfo.get(0).WallPaperMiddle);
System.out.println(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.getMessage());
}
});
//3. 把请求对象,添加到请求队列中
requestQueue.add(strReq);
break;
case R.id.btn_net:
VolleyUtils.getInstance(this).getData(Request.Method.GET, Constant.URL_NET
, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
tv_result.setText(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
break;
}
}
}