Android Volley - Checking internet state

后端 未结 6 1853
耶瑟儿~
耶瑟儿~ 2020-12-08 08:30

Before I am using Volley, well as usual, I used AsyncTask to check my internet state.

Here is what I did in AsyncTask:

private class NetCheck extends         


        
6条回答
  •  -上瘾入骨i
    2020-12-08 09:02

    This is how I make Volley Request and handle response and errors, you don't need to add Async task for this, volley make request in backend

    StringRequest strReq = new StringRequest(Request.Method.POST, "your_url", new Response.Listener() {
                @Override
                public void onResponse(String response) {
    
                    // handle your response here
                    // if your response is a json then create json object and use it
                    try {
                        JSONObject jsonObject = new JSONObject(response);
    
                        // now you can get values from your jsonObject
    
                    }
                    catch (Exception e){}
    
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
    
                    String message = null; // error message, show it in toast or dialog, whatever you want
                    if (volleyError instanceof NetworkError || volleyError instanceof AuthFailureError || volleyError instanceof NoConnectionError || volleyError instanceof TimeoutError) {
                        message = "Cannot connect to Internet";
                    } else if (volleyError instanceof ServerError) {
                        message = "The server could not be found. Please try again later";
                    }  else if (volleyError instanceof ParseError) {
                        message = "Parsing error! Please try again later";
                    }
    
                }
            }) {
                @Override
                public byte[] getBody() throws AuthFailureError {
    
                    HashMap params = new HashMap<>();
                    params.put("key","value"); // put your params here
    
                    return new JSONObject(params).toString().getBytes();
                }
    
                @Override
                public String getBodyContentType() {
                    return "application/json";
                }
            };
            // Adding String request to request queue
    
            Volley.newRequestQueue(getApplicationContext()).add(strReq);
    

提交回复
热议问题