How to get the MAC address of an android device(WIFI is switched off) through code?

回眸只為那壹抹淺笑 提交于 2019-12-03 21:14:30

Here is the code to getMac Address without using wifi manager.

public static String getMACAddress(String interfaceName) {
    try {
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            if (interfaceName != null) {
                if (!intf.getName().equalsIgnoreCase(interfaceName)) continue;
            }
            byte[] mac = intf.getHardwareAddress();
            if (mac==null) return "";
            StringBuilder buf = new StringBuilder();
            for (int idx=0; idx<mac.length; idx++)
                buf.append(String.format("%02X:", mac[idx]));       
            if (buf.length()>0) buf.deleteCharAt(buf.length()-1);
            return buf.toString();
        }
    } catch (Exception ex) { } 
    return "";

}

Some android devices may not have wifi available or are using ethernet wiring. and call this method as per network available.

getMACAddress("wlan0"); //using wifi available
getMACAddress("eth0"); //using ethernet connection availale

and do not forget to set manifest permission.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
user9475162
    private TextView btnInfo;
    private View txtWifiInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtWifiInfo = (TextView) findViewById(R.id.idTxt);
        btnInfo = (Button) findViewById(R.id.idBtn);
    }
    public void getWifiInformation(View view){
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ip = wifiInfo.getIpAddress();
        String macAddress = wifiInfo.getMacAddress();
        String bssid = wifiInfo.getBSSID();



        int rssi = wifiInfo.getRssi();
        int linkspeed = wifiInfo.getLinkSpeed();
        String ssid = wifiInfo.getSSID();
        int networkId = wifiInfo.getNetworkId();
        String ipAddress = Formatter.formatIpAddress(ip);
        String info = "Ipaddress: " + ipAddress +
                "\n" + "MacAddress: " +macAddress +
                "\n" + "BSSID: " + bssid +
                "\n" + "SSID: " + ssid +
                "\n" +  "NetworkId: "+ networkId;
                 // "\n" + "RSSI: " + rssi +
               // "\n" + linkspeed + "Link Speed: ";
        txtWifiInfo.setText(info);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!