2014-01-09 40 views
10

在我使用Volley之前,和往常一樣,我使用AsyncTask來檢查我的互聯網狀態。Android Volley - 檢查互聯網狀態

這是我在做的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; 
} 

如何實現這一目標用排球?

回答

79

有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."; 
    } 
} 
+0

絕對適合我。 – shaiToro

+6

這是不一樣的。 不僅在沒有網絡連接時,而且在無法建立與主機的連接時(例如,如果它無法解析主機),拋出NoConnectionError。 – user2137020

+0

由於'NoConnectionError'擴展了'NetworkError',所以你永遠不會碰到'if(volleyError instanceof NoConnectionError){' – Jon

1

使用此代碼用於檢查網絡狀態:

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; 
     } 
    } 
} 
+0

添加權限在android系統的manifest.xml: <使用許可權的android:NAME =「android.permission.ACCESS_NETWORK_STATE」 /> –

+0

沒有後臺任務,這不會引發錯誤嗎? – AimanB

+0

是的,你可以使用此代碼檢查互聯網連接之前啓動Asyntask –

2

錯誤我用下面的代碼用於檢測錯誤的發生:

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(); 
      } 
     } 
    }); 
0

我管理,檢查互聯網應用類

 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); 

所以每次調用請求之前,這將是執行,如果互聯網可