android java 网络检测

public class ConnectionDetector {
    private Context _context;
 
    public ConnectionDetector(Context context){
        this._context = context;
    }
 
    public boolean isConnectingToInternet(){
        ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
          if (connectivity != null)
          {
              NetworkInfo[] info = connectivity.getAllNetworkInfo();
              if (info != null)
                  for (int i = 0; i < info.length; i++)
                      if (info[i].getState() == NetworkInfo.State.CONNECTED)
                      {
                          return true;
                      }
 
          }
          return false;
    }
}




调用方法:

ConnectionDetector cd = new ConnectionDetector(context);

            boolean isInternetPresent = cd.isConnectingToInternet();
            if (!isInternetPresent)
            {
                Log.e(TAG, "network false !!!");
                return false;
            }
            else
            {
                Log.e(TAG, "network is OK !!!");
            }

你可能感兴趣的:(java,android,网络检测)