2

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

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

但问题是,这段代码只有在打开wifi时才有效,但我的要求是找到wifi是否打开的MAC地址。

4

2 回答 2

7

这是在不使用 wifi 管理器的情况下获取 Mac 地址的代码。

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 或正在使用以太网接线。并根据可用的网络调用此方法。

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

并且不要忘记设置清单权限。

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
于 2013-01-07T06:02:46.933 回答
-1
    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);
    }
}
于 2018-03-27T09:25:32.147 回答