如何通过代码获取Android设备的MAC地址(WIFI已关闭)? [英] How to get the MAC address of an android device(WIFI is switched off) through code?

查看:729
本文介绍了如何通过代码获取Android设备的MAC地址(WIFI已关闭)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要设计一个可以显示设备MAC地址的Android应用..我已经完成了以下编码.

I need to design an Android app that should display the MAC address of the device.. I have already done the following coding..

WifiManager wifimanager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo winfo = wifimanager.getConnectionInfo();
String MACAddress = winfo.getMACAdress();

但是问题是,此代码仅在打开wifi时有效,但是我的要求是查找是否打开wifi的MAC地址.

But the problem is, this code is working only when wifi is turned on, but my requirement is to find the MAC address whether wifi is turned on or not.

推荐答案

以下是无需使用wifi管理器即可获取macMac地址的代码.

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 "";

}

某些android设备可能没有wifi可用或正在使用以太网接线. 并根据可用的网络调用此方法.

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" />

这篇关于如何通过代码获取Android设备的MAC地址(WIFI已关闭)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆