1. 程式人生 > >Android 手機獲取Mac地址的方法

Android 手機獲取Mac地址的方法

轉載地址: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及其以上版本都可以獲取到。

這期需求,要求從系統裝置上獲取一個唯一碼作為當前登入使用者的唯一標識,最後決定採用mac地址。