android判断网络连接状态-ConnectivityManager

android.net.ConnectivityManager主要用于管理与网络连接相关的操作。
需要访问网络,首先需要添加权限

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

示例代码如下:
   protected void testNetwork(){
    ConnectivityManager cm = (ConnectivityManager) this.getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();

     if(networkInfo.isAvailable()){
      Log.i(TAG, "network available");
    } else{
      Log.i(TAG , "network not available");
    }
    
     if(State.CONNECTED == cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState()){
      Log.i(TAG , "gprs is connected");
    }
    
     if(State.CONNECTED == cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState()){
      Log.i(TAG, "wifi is connected");
    }
  }

你可能感兴趣的:(android,网络连接,休闲,网络状态)