Java 以编程方式检索MAC地址-Android
在任何人提到其他帖子之前,我已经阅读过一些帖子,例如: 然而,我尝试在自己的应用程序中使用该代码,并用一个简单的log.d对其进行了测试,结果发现它没有返回任何内容。“看看这是否有效”的信息只表明了这一点。所以我假设mac地址为空Java 以编程方式检索MAC地址-Android,java,android,mac-address,Java,Android,Mac Address,在任何人提到其他帖子之前,我已经阅读过一些帖子,例如: 然而,我尝试在自己的应用程序中使用该代码,并用一个简单的log.d对其进行了测试,结果发现它没有返回任何内容。“看看这是否有效”的信息只表明了这一点。所以我假设mac地址为空 Log.d("seeing if this works", macAddress2); 我所做工作的代码如下所示: //Set onclick listener for the Get Mac Address button getMac.setOn
Log.d("seeing if this works", macAddress2);
我所做工作的代码如下所示:
//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);
}
});
你的舱单上有这个吗
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
您测试的是哪个Android版本?最新版本(2015年10月)阻止该应用获取Wifi和蓝牙的硬件标识符 为了向用户提供更好的数据保护,从本版本开始,Android将删除使用Wi-Fi和蓝牙API的应用程序对设备本地硬件标识符的编程访问。WifiInfo.getMacAddress()和BluetoothAdapter.getAddress()方法现在返回的常量值为02:00:00:00:00 通过从
/sys/class/net/wlan0/address
读取Wifi MAC有一个解决方法,但是在Android Nas中也会被阻止。尝试以下操作:
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";
}
public静态字符串getMacAddr(){
试一试{
List all=Collections.List(NetworkInterface.getNetworkInterfaces());
用于(网络接口nif:all){
如果(!nif.getName().equalsIgnoreCase(“wlan0”))继续;
byte[]macBytes=nif.getHardwareAddress();
if(macBytes==null){
返回“”;
}
StringBuilder res1=新的StringBuilder();
用于(字节b:macBytes){
res1.append(Integer.toHexString(b&0xFF)+“:”;
}
如果(res1.length()>0){
res1.deleteCharAt(res1.length()-1);
}
返回res1.toString();
}
}捕获(例外情况除外){
}
返回“02:00:00:00:00:00”;
}
从这里开始:
适合我。您打电话时是否连接了WiFi?还有,你的AndroidManifest.xml中有什么?嘿,谢谢你的回复,是的,我已经把它放在了manifestStrange中,我使用了你的代码,它对我来说很好。你肯定连接到了Wi-Fi?哦,真的,我是通过android studio emulator运行的,所以我认为它在emulator上不起作用?谢谢你的回复,我已经把它放在我的清单文件中了