Android排球 - 检查互联网状态

Eme*_*men 17 java android android-volley

在我使用Volley之前,像往常一样,我使用AsyncTask来检查我的互联网状态.

这是我在AsyncTask中所做的:

private class NetCheck extends AsyncTask<String, Void, Boolean> {

    @Override
    protected Boolean doInBackground(String... args) {
        // get Internet status
        return cd.isConnectingToInternet();
    }

    protected void onPostExecute(Boolean th) {
        if (th == true) {
            new LoadCategories().execute();
        } else {
            Toast.makeText(CategoryActivity.this, "Unable to connect to server",
                    Toast.LENGTH_LONG).show();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是isConnectingToInternet功能:

public boolean isConnectingToInternet() {
    ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity != null) {
        NetworkInfo info = connectivity.getActiveNetworkInfo();
        if (info != null && info.isConnected())    
            try {
                URL url = new URL("http://www.google.com");
                HttpURLConnection urlc = (HttpURLConnection) url
                        .openConnection();
                urlc.setConnectTimeout(3000);
                urlc.connect();
                if (urlc.getResponseCode() == 200) {
                    return true;
                }
            } catch (MalformedURLException e1) {
                e1.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

我如何使用Volley实现这一目标?

小智 95

为请求抛出NoConnection错误.请抓住错误

   @Override
   public void onErrorResponse(VolleyError volleyError) {
   String message = null;
   if (volleyError instanceof NetworkError) {
         message = "Cannot connect to Internet...Please check your connection!";
   } else if (volleyError instanceof ServerError) {
         message = "The server could not be found. Please try again after some time!!";
   } else if (volleyError instanceof AuthFailureError) {
         message = "Cannot connect to Internet...Please check your connection!";
   } else if (volleyError instanceof ParseError) {
         message = "Parsing error! Please try again after some time!!";
   } else if (volleyError instanceof NoConnectionError) {
         message = "Cannot connect to Internet...Please check your connection!";
   } else if (volleyError instanceof TimeoutError) {
         message = "Connection TimeOut! Please check your internet connection.";
   }
}
Run Code Online (Sandbox Code Playgroud)

  • 这不一样.NoConnectionError不仅在没有网络连接时抛出,而且在无法与主机建立连接时(例如,如果它无法解析主机). (10认同)
  • 由于`NoConnectionError`扩展了`NetworkError`,你永远不会遇到`if(volleyError instanceof NoConnectionError){` (2认同)