学习了郭宏志老师的<爱美食>项目,自己总结和抄写了一份郭宏志老师对volley网络框架的使用(使用volley网络框架来获取聚合数据的API)
开发环境为Android studio
第一步
关联框架
project construct->app->dependencies->”+”->library dependency->输入volley搜索->选择 eu.the4thfloor.volley.com.adroid.volley2015.05.28
然后ok第二步
获取网络权限
在清单注册文件中加入
<uses-permission android:name="android.permission.INTERNET"/>
第三步
编写类
这里提供一个引用老师编写的类,myvolley.java
public class MyVolley {
private static MyVolley myVolley;
public static MyVolley newMyVolley(){
if(myVolley==null){
myVolley=new MyVolley();
}
return myVolley;
}
private CallBack callBack;
private StringRequest stringRequest;
private Context context;
//string get
public void stringRequestGet(Context context,String url,CallBack callBack){
RequestQueue queue= Volley.newRequestQueue(context);
this.callBack=callBack;
stringRequest=new StringRequest(Request.Method.GET,url,stringListener,errorListener);
queue.add(stringRequest);
}
//string post
public void stringRequestPost(Context context, String url, final Map map, CallBack callBack){
RequestQueue queue= Volley.newRequestQueue(context);
this.callBack=callBack;
stringRequest=new StringRequest(Request.Method.POST,url,stringListener,errorListener){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
return map;
}
};
}
//string listener
private Response.Listener<String> stringListener=new Response.Listener<String>(){
@Override
public void onResponse(String response) {
callBack.onStringSuccess(response);
}
};
//error listener
private Response.ErrorListener errorListener=new Response.ErrorListener(){
@Override
public void onErrorResponse(VolleyError error) {
callBack.onFailure(error);
}
};
public interface CallBack{
public void onStringSuccess(String response);
public void onFailure(VolleyError error);
}
}
就可以使用了。
这是一点总结,Android小白还在学习中。