zoukankan      html  css  js  c++  java
  • 在安卓6.0(及以上)设备上无法获取无线网卡MAC地址的解决方案

    在安卓6.0以下的设备上,通过WifiManager.getConnectionInfo().getMacAddress()即可获取WLAN物理地址,

    而在6.0及以上,以此方式获取到的MAC地址为固定值02:00:00:00:00:00,而非真实值

    解决方案

    WlanMacAddressGetter.java

    package com.example.buyishi.myapplication;
    
    import android.util.Log;
    
    import java.net.NetworkInterface;
    import java.net.SocketException;
    import java.util.Enumeration;
    
    public class WlanMacAddressGetter {
        private static final String TAG = WlanMacAddressGetter.class.getName();
    
        public static String getWlanMacAddress() {
            try {
                Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
                while (networkInterfaces.hasMoreElements()) {
                    NetworkInterface networkInterface = networkInterfaces.nextElement();
                    if (networkInterface.getName().equals("wlan0")) {
                        StringBuilder mac = new StringBuilder();
                        byte[] hardwareAddress = networkInterface.getHardwareAddress();
                        String hex = Integer.toHexString(hardwareAddress[0] & 0xff);
                        if (hex.length() == 1) {
                            mac.append('0');
                        }
                        mac.append(hex);
                        for (int i = 1; i < hardwareAddress.length; ++i) {
                            mac.append(':');
                            hex = Integer.toHexString(hardwareAddress[i] & 0xff);
                            if (hex.length() == 1) {
                                mac.append('0');
                            }
                            mac.append(hex);
                        }
                        return mac.toString();
                    }
                }
            } catch (SocketException ex) {
                Log.e(TAG, null, ex);
            }
            return null;
        }
    }

    注意:须声明权限android.permission.INTERNET,否则在获取MAC时会引发SocketException

  • 相关阅读:
    近期Android学习II
    近期Android学习
    Java中AQS基本实现原理
    Java中CAS 基本实现原理
    SpringBoot 消息国际化配置
    SpringBoot2.0 配置多数据源
    浅谈Java 线程池原理及使用方式
    Java并发编程之闭锁与栅栏
    Java 8 Stream API实例
    第二阶段考试
  • 原文地址:https://www.cnblogs.com/buyishi/p/10049196.html
Copyright © 2011-2022 走看看