Android 判断是否连接网络

android判断是否连接网络

判断wifi网络是否链接


复制代码
 1 public static boolean isWiFiActive(Context inContext) {
 2         WifiManager mWifiManager = (WifiManager) inContext
 3         .getSystemService(Context.WIFI_SERVICE);
 4         WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
 5         int ipAddress = wifiInfo == null ? 0 : wifiInfo.getIpAddress();
 6         if (mWifiManager.isWifiEnabled() && ipAddress != 0) {
 7         System.out.println("**** WIFI is on");
 8             return true;
 9         } else {
10             System.out.println("**** WIFI is off");
11             return false;   
12         }
13 }
复制代码

判断3G网络是否链接

 

复制代码
  public static boolean isNetworkAvailable( Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                if (connectivity == null) {
                      System.out.println("**** newwork is off");
                        return false;
                } else {
                        NetworkInfo info = connectivity.getActiveNetworkInfo();
                        if(info == null){
                              System.out.println("**** newwork is off");
                                return false;
                        }else{
                                if(info.isAvailable()){
                                      System.out.println("**** newwork is on");
                                        return true;
                                }
                              
                        }
                }
                  System.out.println("**** newwork is off");
        return false;
    }
复制代码


 相关权限

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


你可能感兴趣的:(android,网络,service,null,NetWork)