Android获取手机当前连接的WiFi信息(SSID,IP,连接状态)

1、AndroidMainfest.xml文件中添加权限

   
   

2、获取wifi的ssid

/**
     * 获取当前连接WIFI的SSID
     */
    public String getSSID() {
        WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
        if (wm != null) {
            WifiInfo winfo = wm.getConnectionInfo();
            if (winfo != null) {
                String s = winfo.getSSID();
                if (s.length() > 2 && s.charAt(0) == '"' && s.charAt(s.length() - 1) == '"') {
                    return s.substring(1, s.length() - 1);
                }
            }
        }
        return "";
    }

3、获取WiFi连接的ip地址

public static InetAddress getWifiIp() {
        Context myContext = Globals.getContext();
        if (myContext == null) {
            throw new NullPointerException("Global context is null");
        }
        WifiManager wifiMgr = (WifiManager) myContext.getSystemService(Context.WIFI_SERVICE);
        if (isWifiEnabled()) {
            int ipAsInt = wifiMgr.getConnectionInfo().getIpAddress();
            if (ipAsInt == 0) {
                return null;
            } else {
                return Util.intToInet(ipAsInt);
            }
        } else {
            return null;
        }
    }
// 取得wifi的ip地址
  InetAddress address = FTPServerService.getWifiIp();
  address.getHostAddress();

4、判断WiFi是否连接

public static boolean isWifiEnabled() {
        Context myContext = Globals.getContext();
        if (myContext == null) {
            throw new NullPointerException("Global context is null");
        }
        WifiManager wifiMgr = (WifiManager) myContext.getSystemService(Context.WIFI_SERVICE);
        if (wifiMgr.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
            ConnectivityManager connManager = (ConnectivityManager) myContext
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo wifiInfo = connManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            return wifiInfo.isConnected();
        } else {
            return false;
        }
    }

5、打开wifi设置的页面

Intent intent = new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS);
startActivity(intent);

完!!!

补充:

//将获取的int转为真正的ip地址,参考的网上的,修改了下  
private String intToInet(int i)  {
  return (i & 0xFF)+ "." + ((i >> 8 ) & 0xFF)? + "." + ((i >> 16 ) & 0xFF) +"."+((i >> 24 ) & 0xFF );
} 

 

你可能感兴趣的:(android)