【问题标题】:Android Volley - Checking internet stateAndroid Volley - 检查互联网状态
【发布时间】:2014-01-09 03:48:34
【问题描述】:

在我使用 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();
        }
    }
}

这是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;
}

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

【问题讨论】:

    标签: java android android-volley


    【解决方案1】:

    请求引发了 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.";
       }
    }
    

    【讨论】:

    • 这不一样。 NoConnectionError 不仅在没有网络连接时抛出,而且在无法与主机建立连接时(例如,如果它无法解析主机)。
    • 由于NoConnectionError 扩展了NetworkError,你永远不会碰到if (volleyError instanceof NoConnectionError) {
    【解决方案2】:

    这就是我发出 Volley 请求并处理响应和错误的方式,您不需要为此添加异步任务,在后端进行 volley 请求

    StringRequest strReq = new StringRequest(Request.Method.POST, "your_url", new Response.Listener<String>() {
                @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<String, String> 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);
    

    【讨论】:

      【解决方案3】:

      我使用下面的代码来检测正在发生的错误:

       new Response.ErrorListener() {
      
              @Override
              public void onErrorResponse(VolleyError error) {
      
      
                  if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                      Toast.makeText(getApplicationContext(), "Communication Error!", Toast.LENGTH_SHORT).show();
      
                  } else if (error instanceof AuthFailureError) {
                      Toast.makeText(getApplicationContext(), "Authentication Error!", Toast.LENGTH_SHORT).show();
                  } else if (error instanceof ServerError) {
                      Toast.makeText(getApplicationContext(), "Server Side Error!", Toast.LENGTH_SHORT).show();
                  } else if (error instanceof NetworkError) {
                      Toast.makeText(getApplicationContext(), "Network Error!", Toast.LENGTH_SHORT).show();
                  } else if (error instanceof ParseError) {
                      Toast.makeText(getApplicationContext(), "Parse Error!", Toast.LENGTH_SHORT).show();
                  }
              }
          });
      

      【讨论】:

        【解决方案4】:

        使用此代码检查互联网状态:

        public class Internet {
            private Context context;
        
            public Internet(Context context) {
                this.context = context;
            }
        
            public Boolean Check() {
                ConnectivityManager cn = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo nf = cn.getActiveNetworkInfo();
                if (nf != null && nf.isConnected() == true) {
                    return true;
                } else {
                    Toast.makeText(context, "No internet connection.!",
                            Toast.LENGTH_LONG).show();
                    return false;
                }
            }
        }
        

        【讨论】:

        • 在 android manifest.xml 中添加权限:
        • 是的,您可以在启动 Asyntask 之前使用此代码检查互联网连接
        • 但我不想使用 AsyncTask。可以用 Volley 代替吗?
        • 是的,可以。如果你想从服务器加载图像到列表视图,你可以使用 smartImageView :loopj.com/android-smart-image-view
        • 您好,请查看arnab.ch/blog/2013/08/…。希望它会向您解释您想要做什么,我认为您可以在我的回答中遵循给定的方法。我觉得它真的很棒很合适
        【解决方案5】:

        我设法在应用程序类中检查互联网

             public class App extends Application {
                    private static final String TAG = "MyApp";
        
                    private static App mInstance;
                    private RequestQueue mRequestQueue;
                    private ImageLoader mImageLoader;
        
                    public static synchronized App getInstance() {
                        return mInstance;
                    }
        
                    @Override
                    public void onCreate() {
                        super.onCreate();
                      mInstance = this;
                    }
        
                    public RequestQueue getRequestQueue() {
                        if (mRequestQueue == null) {
                            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
                        }
        
                        return mRequestQueue;
                    }
        
        
        
                    public <T> void addToRequestQueue(Request<T> req, String tag) {
                        // set the default tag if tag is empty
                        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
                        getRequestQueue().add(req);
                    }
        
                    public <T> void addToRequestQueue(Request<T> req) {
        
                        if(CommonUtills.isNetworkAvailable(getApplicationContext())) {
                            req.setRetryPolicy(new DefaultRetryPolicy(
                                    60000,
                                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                            req.setTag(TAG);
                            getRequestQueue().add(req);
                        }
                        else
                        {
                         Toast.makeText(getApplicationContext(), "Unable to 
        connect to server",Toast.LENGTH_LONG).show();
                        }
                    }
        
                    public void cancelPendingRequests(Object tag) {
                        if (mRequestQueue != null) {
                            mRequestQueue.cancelAll(tag);
                        }
                    }
        
                }
        

        我每次都使用以下方式调用每个网络调用

        App.getInstance().addToRequestQueue(jsonObjRequest);
        

        所以在调用每个请求之前,如果互联网可用,它将被执行

        【讨论】:

          【解决方案6】:
          new Response.ErrorListener() {
          
              @Override
              public void onErrorResponse(VolleyError volleyError) {
          
                  if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
                      Toast.makeText(getApplicationContext(), "No Connection/Communication Error!", Toast.LENGTH_SHORT).show();
          
                  } else if (volleyError instanceof AuthFailureError) {
                      Toast.makeText(getApplicationContext(), "Authentication/ Auth Error!", Toast.LENGTH_SHORT).show();
                  } else if (volleyError instanceof ServerError) {
                      Toast.makeText(getApplicationContext(), "Server Error!", Toast.LENGTH_SHORT).show();
                  } else if (volleyError instanceof NetworkError) {
                      Toast.makeText(getApplicationContext(), "Network Error!", Toast.LENGTH_SHORT).show();
                  } else if (volleyError instanceof ParseError) {
                      Toast.makeText(getApplicationContext(), "Parse Error!", Toast.LENGTH_SHORT).show();
                  }
              }
          });
          

          这对您作为开发人员有好处。但是不要向最终用户显示一些直接消息,例如身份验证和服务器端错误。发挥创意,展示目前无法连接的情况。

          【讨论】:

            猜你喜欢
            • 2015-03-25
            • 1970-01-01
            • 2012-06-12
            • 2016-09-10
            • 1970-01-01
            • 1970-01-01
            • 2016-08-28
            • 1970-01-01
            • 2017-11-30
            相关资源
            最近更新 更多