今日發現一個問題,系統要求從設備上獲取一個唯一碼作為當前登錄用戶的唯一標識;
之前嘗試過很多方法,最后決定采用mac地址。
官方獲取mac地址的方法是:
public static String getWifiMac(Context ctx) {
WifiManager wifi = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
String str = info.getMacAddress();
if (str == null) str = "";
return str;
}
但是最后發現,某些設備上(比如樂視2手機,谷歌的Nexus9 pad),用這種方式獲取的mac地址都是02:00:00:00:00:00 .
並不能起到唯一標識的作用。
后來發現,Android的內核是linux,那么應該可以通過shell命令的方式來獲取。
代碼如下:
/**
* 這是使用adb shell命令來獲取mac地址的方式
* @return
*/
public static String getMac() {
String macSerial = null;
String str = "";
try {
Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address ");
InputStreamReader ir = new InputStreamReader(pp.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
for (; null != str; ) {
str = input.readLine();
if (str != null) {
macSerial = str.trim();// 去空格
break;
}
}
} catch (IOException ex) {
// 賦予默認值
ex.printStackTrace();
}
return macSerial;
}
解決上述兩種設備上mac地址獲取錯誤的問題。
可見,就算是谷歌官方給出的解決方案也未必可靠,要根據實際情況酌情考慮使用。
另外,嘗試了一下在4G網絡下獲取mac地址,結果是null。說明 4G網絡下不會有mac地址這一說,因為根本獲取不到。3G網也應該類似(沒做試驗)。
但是有些設備,運行shell命令會報錯:權限被拒絕。(Nexus 9 pad親測,這個方法不靈);這就很尷尬了。。
