Android_获取本机的Mac地址

获取本机的Mac地址

大家可能在 写项目的时候需要用到 mac地址 之前小编在刚开始获取的时候遇到了一些坑 比如支持的

Android版本可能只是支持6.0的 所以 在这里我整理了一下可以直接用
以下是整理的代码

/**
 * 作者:NB的LittleWhite
 * <p>
 * 邮箱:[email protected]
 */
public class IpMacAddress {
    public static String getMacAddress(){
        /*获取mac地址有一点需要注意的就是android 6.0版本后,以下注释方法不再适用,不管任何手机都会返回"02:00:00:00:00:00"这个默认的mac地址,这是googel官方为了加强权限管理而禁用了getSYstemService(Context.WIFI_SERVICE)方法来获得mac地址。*/
        //    String macAddress= "";
//    WifiManager wifiManager = (WifiManager) MyApp.getContext().getSystemService(Context.WIFI_SERVICE);
//    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
//    macAddress = wifiInfo.getMacAddress();
//    return macAddress;
        String macAddress = null;
        StringBuffer buf = new StringBuffer();
        NetworkInterface networkInterface = null;
        try {
            networkInterface = NetworkInterface.getByName("eth1");
            if (networkInterface == null) {
                networkInterface = NetworkInterface.getByName("wlan0");
            }
            if (networkInterface == null) {
                return "02:00:00:00:00:02";
            }
            byte[] addr = networkInterface.getHardwareAddress();
            for (byte b : addr) {
                buf.append(String.format("%02X:", b));
            }
            if (buf.length() > 0) {
                buf.deleteCharAt(buf.length() - 1);
            }
            macAddress = buf.toString();
        } catch (SocketException e) {
            e.printStackTrace();
            return "02:00:00:00:00:02";
        }
        return macAddress;
    }

}

在这里返回的就直接是 本机Mac地址 小编亲自试验过 我用的平板‘Android
版本是7.0 的可以直接使用

猜你喜欢

转载自blog.csdn.net/weixin_43430682/article/details/107465512