网络工具框架Volley

App类:
public class ShowApp extends Application {

    public static  RequestQueue requestQueue;

    @Override
    public void onCreate() {
        super.onCreate();
       requestQueue = Volley.newRequestQueue(getApplicationContext());
Thread.setDefaultUncaughtExceptionHandler(CrashHandler.getInstance(this));
    }
    public static RequestQueue getVolley(){
        return requestQueue;
    }
}
Volley类:
public class Volley {
    public static Context context;
    public static Volley volley;

 public boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    public static synchronized Volley getInstance() {

        if (volley == null) {
            volley=new Volley();
        }
        return volley;
    }

    public void VolleyGet(String url, final VolleyCallBack callback) {

        StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                callback.success(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                callback.fail(error);
            }
        });
        stringRequest.setTag("GET");
        ShowApp.getVolley().add(stringRequest);
    }

    public interface VolleyCallBack {

        public void success(String data);
        public void fail(VolleyError error);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43584998/article/details/89438299