Android获取WifiMac地址

Android获取WifiMac地址

1:android6.0以下通过wifiinfo来获取。

WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                if (wifi != null) {
                    WifiInfo wifiInfo = wifi.getConnectionInfo();
                    if (wifiInfo != null) {
                        macAddress = wifiInfo.getMacAddress();
                    }
                }

另外需要添加权限:

  
    
    

    
    

2:6.0以上

通过NetworkInterface获取。

   NetworkInterface intf;
                Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
                while (interfaces.hasMoreElements()) {
                    intf = interfaces.nextElement();
                    if (null == intf ||
                            !TextUtils.equals("wlan0", intf.getName().toLowerCase())
                    ) {
                        continue;
                    }

                    final byte[] mac = intf.getHardwareAddress();
                    if (mac != null) {
                        StringBuilder buf = new StringBuilder();
                        for (byte aMac : mac) {
                            buf.append(String.format("%02X:", aMac));
                        }
                        if (buf.length() > 0) {
                            buf.deleteCharAt(buf.length() - 1);
                        }
                        macAddress = buf.toString();
                    }
                    break;
                }

3:由于10.0后引入了随机mac的概念。

方法2会在部分机型上面返回的是随机mac.

这里目前只能通过强管控deviceOnwer的状况下调用以下方法来获取设备的wifimac。

 
devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
componentName = new ComponentName(this, MyDeviceAdminReceiver.class);
 String wifiMac = devicePolicyManager.getWifiMacAddress(componentName) == null ? "" : devicePolicyManager.getWifiMacAddress(componentName);

你可能感兴趣的:(设备管控,安卓,android,wifi,mac,移动开发)