Android6及以上版本获取MAC地址

为给用户提供更严格的数据保护,从 Android 6.0 (Marshmallow) 版本开始,对于使用 WLAN API 和 Bluetooth API 的应用,Android 移除了对设备本地硬件标识符的编程访问权。WifiInfo.getMacAddress() 方法和 BluetoothAdapter.getAddress() 方法现在会返回常量值 02:00:00:00:00:00。

现在,要通过蓝牙和 WLAN 扫描访问附近外部设备的硬件标识符,您的应用必须拥有 ACCESS_FINE_LOCATION 或 ACCESS_COARSE_LOCATION 权限。

refer Android 6.0 变更

注意:不要傻傻的以为添加了 ACCESS_FINE_LOCATION 或 ACCESS_COARSE_LOCATION 权限就能访问自己应用所在手机的MAC地址了,上面说的是扫描附近别的设备的硬件标识符。

目前的可替代方案

public String getMacAddr() {
    try {
        List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface nif : all) {
            if (!nif.getName().equalsIgnoreCase("wlan0")) continue;

            byte[] macBytes = nif.getHardwareAddress();
            if (macBytes == null) {
                return "";
            }

            StringBuilder res = new StringBuilder();
            for (byte b : macBytes) {
                res.append(String.format("%02X:",b));
            }

            if (res.length() > 0) {
                res.deleteCharAt(res.length() - 1);
            }

            return res.toString();
        }
    } catch (Exception ex) {
        Log.w("MacAddr", "exception during retrieving MAC address: " + ex.getMessage());
    }

    return "02:00:00:00:00:00";
}

该方案可行的条件是保证WLAN(WiFi)处于开启状态,能不能访问网络不是必要条件。

refer Android 6.0 - You CAN NO longer access the Mac-Address? You can !

猜你喜欢

转载自xuanzhui.iteye.com/blog/2377413