问题
I'm having an issue with retrieving the MAC address of the device programatically, before anyone mentions anything about other posts I have read them already such as: How to find MAC address of an Android device programmatically
however I tried using the code with my own application and tested it with a simple log.d, only to find that it is returning nothing. The message of "seeing if this works shows" but nothing else. So i am presuming the mac address is null.
Log.d("seeing if this works", macAddress2);
The code of what I have done is shown here:
//Set onclick listener for the Get Mac Address button
getMac.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
String macAddress2 = wInfo.getMacAddress();
macAddress.setText(macAddress2);
}
});
回答1:
Which Android version are you testing on? The latest(10/2015) Android M preview has blocked the app from getting the hardware identifiers for Wifi and Bluetooth.
To provide users with greater data protection, starting in this release, Android removes programmatic access to the device’s local hardware identifier for apps using the Wi-Fi and Bluetooth APIs. The WifiInfo.getMacAddress() and the BluetoothAdapter.getAddress() methods now return a constant value of 02:00:00:00:00:00.
There is a workaround by reading the Wifi MAC from /sys/class/net/wlan0/address
, which however will also be blocked in the Android N as claimed by Google.
回答2:
Try this:
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(Integer.toHexString(b & 0xFF) + ":");
}
if (res1.length() > 0) {
res1.deleteCharAt(res1.length() - 1);
}
return res1.toString();
}
} catch (Exception ex) {
}
return "02:00:00:00:00:00";
}
From here: http://robinhenniges.com/en/android6-get-mac-address-programmatically
Works for me.
回答3:
Do you have this in the manifest?
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
来源:https://stackoverflow.com/questions/29550896/retrieving-mac-address-programmatically-android