Android Google网络连接的判断 - chuwuwang/ReadingNote GitHub Wiki

Google关于在Android BasicNetworking Sample中对网络连接判断的代码片段:

    /**
     * Check whether the device is connected, and if so, whether the connection
     * is wifi or mobile (it could be something else).
     */
    private void checkNetworkConnection() {
      // BEGIN_INCLUDE(connect)
      ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
      NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
      if (activeInfo != null && activeInfo.isConnected()) {
          wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
          mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
          if(wifiConnected) {
              Log.i(TAG, "The active connection is wifi.");
          } else if (mobileConnected){
              Log.i(TAG, "The active connection is mobile.");
          } else {
              Log.i(TAG, "The active connection.");
          }
      } else {
          Log.i(TAG, "No wireless or mobile connection.");
      }
      // END_INCLUDE(connect)
    }