Get Bluetooth local mac address in Marshmallow

前端 未结 8 530
半阙折子戏
半阙折子戏 2020-11-29 06:23

Pre Marshmallow my app would obtain it\'s device MAC address via BluetoothAdapter.getDefaultAdapter().getAddress().

Now with Marshmallow Android is retu

8条回答
  •  情书的邮戳
    2020-11-29 07:06

    You can access Mac address from the file "/sys/class/net/" + networkInterfaceName+ "/address" ,where networkInterfaceName can be wlan0 or eth1.But Its permission may be read-protected,so it may not work in some devices. I am also attaching the code part which i got from SO.

    public static String getWifiMacAddress() {
            try {
                String interfaceName = "wlan0";
                List interfaces = Collections
                        .list(NetworkInterface.getNetworkInterfaces());
                for (NetworkInterface intf : interfaces) {
                    if (!intf.getName().equalsIgnoreCase(interfaceName)) {
                        continue;
                    }
    
                    byte[] mac = intf.getHardwareAddress();
                    if (mac == null) {
                        return "";
                    }
    
                    StringBuilder buf = new StringBuilder();
                    for (byte aMac : mac) {
                        buf.append(String.format("%02X:", aMac));
                    }
                    if (buf.length() > 0) {
                        buf.deleteCharAt(buf.length() - 1);
                    }
                    return buf.toString();
                }
            } catch (Exception exp) {
    
                exp.printStackTrace();
            } 
            return "";
        }
    

提交回复
热议问题