這篇文章主要介紹了Android 6.0擷取wifi Mac位址為02:00:00:00:00:00的解決方法,非常不錯,具有參考借鑒價值,需要的朋友可以參考下
前言:
之前項目比較舊,手機版本還比較低,還使用eclipse開發。用到了需要擷取手機wifi Mac位址。使用了如下代碼:
// Android 6.0之前的版本可以用的方法(模拟器可以使用)
private String getMacAddrOld()
{
String macString = "";
WifiManager wifimsg = (WifiManager)getSystemService(Context.WIFI_SERVICE);
if (wifimsg != null)
{
if (wifimsg.getConnectionInfo() != null)
{
if (wifimsg.getConnectionInfo().getMacAddress() != null)
{
macString = wifimsg.getConnectionInfo().getMacAddress();
}
}
}
return macString;
}
▲ 産生問題 :
使用這個方法,在模拟器上是可以正常擷取wifi mac位址,但是在Android 6.0系統上,擷取的就有問題,傳回的是“02:00:00:00:00:00”
▲ 問題分析 :
原來谷歌官方為了給使用者更多的資料保護,從這個6.0版本開始, Android 移除了通過 WiFi 和藍牙 API 來在應用程式中可程式設計的通路本地硬體标示符。現在 WifiInfo.getMacAddress() 和 BluetoothAdapter.getAddress() 方法都将傳回 02:00:00:00:00:00
▲ 解決方案 :
正所謂上有政策,下有對策。我們可以使用如下代碼去擷取手機wifi Mac位址,同樣可以解決6.0以上版本問題。值得注意的是模拟器使用如下代碼去擷取是擷取不到的!
public static String getMacAddr() {
try {
List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif : all) {
if (!nif.getName().equalsIgnoreCase("wlan0")) continue;
byte[] macBytes = nif.getHardwareAddress();
if (macBytes == null) {
return "";
}
StringBuilder res1 = new StringBuilder();
for (byte b : macBytes) {
res1.append(String.format("%02X:",b));
}
if (res1.length() > 0) {
res1.deleteCharAt(res1.length() - 1);
}
return res1.toString();
}
} catch (Exception ex) {
}
return "02:00:00:00:00:00";
}
手機必須是有網絡的狀态下,同時注意不要忘了添權重限
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
總結