Getting the MAC address of the device- when wifi is off

微笑、不失礼 提交于 2019-11-29 09:33:30

问题


I am finding the MAC address of the Android Device using the following code:

WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = manager.getConnectionInfo();
String address = info.getMacAddress());

But in this case I am unable to get the MAC address when the Wifi is off. How can I get the MAC address of the Android Device even when WIFI is off.

Thanks


回答1:


Why not enable the Wifi momentarily until you get the MAC address and then disable it once you are done getting the MAC address?

Of course, doing this is if getting the MAC address is absolutely important.

UNTESTED CODE

WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);

if(wifiManager.isWifiEnabled()) {
    // WIFI ALREADY ENABLED. GRAB THE MAC ADDRESS HERE
    WifiInfo info = wifiManager.getConnectionInfo();
    String address = info.getMacAddress();
} else {
    // ENABLE THE WIFI FIRST
    wifiManager.setWifiEnabled(true);

    // WIFI IS NOW ENABLED. GRAB THE MAC ADDRESS HERE
    WifiInfo info = wifiManager.getConnectionInfo();
    String address = info.getMacAddress();
}

You will need these permission setup in the Manifest

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>

I am not entirely sure if the UPDATE_DEVICE_STATS permission is necessary in this case. Please try it out before deciding to keep it.



来源:https://stackoverflow.com/questions/14949872/getting-the-mac-address-of-the-device-when-wifi-is-off

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!