Volley的简单二次封装(个人笔记)

1.最重要最容易忽略的“注册”,在AndroidManifest中输入 name。
例如:android:name=".Volley.VolleyApplication"
2.创建3个类

public class NetworkUtils {
    private static NetworkUtils networkUtils;

    public static NetworkUtils getNetworkUtils() {
        if (networkUtils == null) {
            synchronized (NetworkUtils.class) {
                if (networkUtils == null) {
                    networkUtils = new NetworkUtils();
                }
            }
        }
        return networkUtils;
    }

    private RequestQueue requestQueue = VolleyApplication.requestQueue;


    public void VolleyPost(String url, JSONObject jsonObject, final Handler handler, final int what) {

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(JsonObjectRequest.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Message message = Message.obtain();
                message.what = what;
                message.obj = response.toString();
                handler.sendMessage(message);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                Log.i("TAG", "onErrorResponse: "+error.toString());
            }
        });
        requestQueue.add(jsonObjectRequest);


    }}

public class VolleyApplication extends Application {
public  static RequestQueue requestQueue;

    @Override
    public void onCreate() {
        super.onCreate();
        requestQueue= VolleyUtils.getRequestQueue(this);
    }

}

    public class VolleyUtils {
    private static RequestQueue requestQueue;

    public static RequestQueue getRequestQueue(Context context) {
        if (requestQueue==null){
            synchronized (RequestQueue.class){
                if (requestQueue==null){
                    requestQueue= Volley.newRequestQueue(context);
                }
            }
        }
        return requestQueue;
    }
}

3.运用方法:

NetworkUtils.getNetworkUtils().VolleyPost(path,jsonObject,mHandler,what);

你可能感兴趣的:(学习资料)