XAMARIN Android获取WIFIMAC地址的方法

对于XAMARIN ANDROID的使用,注意参考官方网站的相关资料。https://developer.xamarin.com/api/type/Android.Net.Wifi.WifiInfo/

1. 常用方法,调用Android的API:WifiManager

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
return info.getMacAddress();

此方法需要保证WIFI在本次开机以来曾经是打开过的,否则会返回null。所以需要后台尝试先打开WIFI再获取。

示例代码:

//尝试打开wifi
private static boolean tryOpenMAC(WifiManager manager)
{
boolean softOpenWifi = false;
int state = manager.getWifiState();
if (state != WifiManager.WIFI_STATE_ENABLED && state != WifiManager.WIFI_STATE_ENABLING)
{
manager.setWifiEnabled(true);
softOpenWifi = true;
}
return softOpenWifi;
}

//尝试关闭MAC
private static void tryCloseMAC(WifiManager manager)
{
manager.setWifiEnabled(false);
}

//尝试获取MAC地址
private static String tryGetMAC(WifiManager manager)
{
WifiInfo wifiInfo = manager.getConnectionInfo();
if (wifiInfo == null || StringUtil.isNull(wifiInfo.getMacAddress()))
{
return null;
}
String mac = wifiInfo.getMacAddress().replaceAll(":", "").trim().toUpperCase();
mac = formatIdentify(mac);
return mac;
}

//尝试读取MAC地址
private static String getMacFromDevice(int internal)
{
String mac=null;
WifiManager wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
mac = tryGetMAC(wifiManager);
if(!StringUtil.isNull(mac))
{
return mac;
}

//获取失败,尝试打开wifi获取
boolean isOkWifi = tryOpenMAC(wifiManager);
for(int index=0;index {
//如果第一次没有成功,第二次做100毫秒的延迟。
if(index!=0)
{
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
mac = tryGetMAC(wifiManager);
if(!StringUtil.isNull(mac))
{
break;
}
}

//尝试关闭wifi
if(isOkWifi)
{
tryCloseMAC(wifiManager);
}
return mac;
}

==================================================================

2. 查询文件路径 /sys/class/net/wlan0/address

adb shell cat /sys/class/net/wlan0/address

98:6c:f5:10:96:c4

但是如果WIFI在本次开机期间从来没有打开过,返回的MAC地址是不同的(非实际的),如下:

cat /sys/class/net/wlan0/address
00:90:4c:11:22:33

示例代码:

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 e) {
e.printStackTrace();
}
return macSerial;
}
==================================================================

3. 查询记录了MAC地址的文件“/proc/net/arp”,但是从测试结果看,返回的数据并不是想要的Wifi Mac地址:

比如,手机实际的WIFI Mac地址是98:6c:f5:10:96:c4,但使用adb shell cat proc/net/arp返回的是:

cat proc/net/arp
IP address HW type Flags HW address Mask Device
192.168.0.3 0x1 0x2 00:23:89:b9:1a:fd * wlan0
192.168.0.1 0x1 0x2 08:00:27:7c:65:5a * wlan0





你可能感兴趣的:(XAMARIN Android获取WIFIMAC地址的方法)