Android 手机获取Mac地址的方法

转载地址:https://blog.csdn.net/yushuangping/article/details/83245847

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yushuangping/article/details/83245847

这期需求,要求从系统设备上获取一个唯一码作为当前登录用户的唯一标识,最后决定采用mac地址。

第一种:

官方获取mac地址的方法是:


  
  
  1. /**
  2. * 通过WiFiManager获取mac地址
  3. * @param context
  4. * @return
  5. */
  6. private static String tryGetWifiMac(Context context) {
  7. WifiManager wm = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
  8. WifiInfo wi = wm.getConnectionInfo();
  9. if (wi == null || wi.getMacAddress() == null) {
  10. return null;
  11. }
  12. if ( "02:00:00:00:00:00".equals(wi.getMacAddress().trim())) {
  13. return null;
  14. } else {
  15. return wi.getMacAddress().trim();
  16. }
  17. }

这个方法Android 7.0是获取不到的,返回的是null,其实是返回“02:00:00:00:00:00”

第二种方法:

通过shell命令的方式来获取:


  
  
  1. **
  2. * 这是使用adb shell命令来获取mac地址的方式
  3. * @return
  4. */
  5. public static String getMac() {
  6. String macSerial = null;
  7. String str = "";
  8. try {
  9. Process pp = Runtime.getRuntime().exec( "cat /sys/class/net/wlan0/address ");
  10. InputStreamReader ir = new InputStreamReader(pp.getInputStream());
  11. LineNumberReader input = new LineNumberReader(ir);
  12. for (; null != str; ) {
  13. str = input.readLine();
  14. if (str != null) {
  15. macSerial = str.trim(); // 去空格
  16. break;
  17. }
  18. }
  19. } catch (IOException ex) {
  20. // 赋予默认值
  21. ex.printStackTrace();
  22. }
  23. return macSerial;
  24. }

这种方式Android7.0以上版本也是获取不到

第三种方法:

根据网络接口获取:


  
  
  1. /**
  2. * 通过网络接口取
  3. * @return
  4. */
  5. private static String getNewMac() {
  6. try {
  7. List<NetworkInterface> all = Collections. list(NetworkInterface.getNetworkInterfaces());
  8. for (NetworkInterface nif : all) {
  9. if (!nif.getName().equalsIgnoreCase( "wlan0")) continue;
  10. byte[] macBytes = nif.getHardwareAddress();
  11. if (macBytes == null) {
  12. return null;
  13. }
  14. StringBuilder res1 = new StringBuilder();
  15. for (byte b : macBytes) {
  16. res1.append(String.format( "%02X:", b));
  17. }
  18. if (res1.length() > 0) {
  19. res1.deleteCharAt(res1.length() - 1);
  20. }
  21. return res1.toString();
  22. }
  23. } catch ( Exception ex) {
  24. ex.printStackTrace();
  25. }
  26. return null;
  27. }

注意网络接口的Name有很多:dummy0、p2p0、wlan0….其中wlan0就是我们需要WiFi mac地址。这个方法Android 7.0及其以上版本都可以获取到。

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yushuangping/article/details/83245847

这期需求,要求从系统设备上获取一个唯一码作为当前登录用户的唯一标识,最后决定采用mac地址。

猜你喜欢

转载自blog.csdn.net/shuijianbaozi/article/details/84869687