如何正确获取 wifi mac地址

获取wifi mac地址

今日研读讯飞 AIUI SDK 对其工具类的实现 进行一下简单记录 正式版本中使用的功能 值得我们借鉴

getWifiMac

为每一个设备设置对应唯一的SN(最好使用设备硬件信息(mac地址,设备序列号等)生成),以便正确统计装机量,避免刷机或者应用卸载重装导致装机量重复计数


/**

  \* 获取Wifi Mac 默认值空字符串

  *

  \* @param paramContext

  \* @return

  */

 public static String getWifiMac(Context paramContext) {String result = "";if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {try {Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();while (interfaces != null && interfaces.hasMoreElements()) {NetworkInterface iF = interfaces.nextElement();byte[] addr = iF.getHardwareAddress();if (addr == null || addr.length == 0) {continue;}//其他网卡(如rmnet0)的MAC,跳过if ("wlan0".equalsIgnoreCase(iF.getName()) || "eth0".equalsIgnoreCase(iF.getName())) {StringBuilder buf = new StringBuilder();for (byte b : addr) {

​              buf.append(String.format("%02X:", b));}if (buf.length() > 0) {

​              buf.deleteCharAt(buf.length() - 1);}String mac = buf.toString();if (mac.length() > 0) {

​              result = mac;return result;}}}} catch (Exception e) {Log.w(TAG, e.toString());}} else {try {// MAC地址WifiManager wifi = (WifiManager) paramContext.getApplicationContext().getSystemService(Context.WIFI_SERVICE);if (wifi != null) {WifiInfo wiinfo = wifi.getConnectionInfo();

​          result = wiinfo.getMacAddress();}} catch (Throwable e) {Log.w(TAG, "Failed to get mac Info");}}return result;

 }

总结

正式商用的功能 仅供参考


版权声明:本文为wnw_jackie原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。