我需要设计一款Android应用,应该显示设备的MAC地址。我已经做了以下编码..
WifiManager wifimanager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo winfo = wifimanager.getConnectionInfo();
String MACAddress = winfo.getMACAdress();
但问题是,当无线网络连接开启此代码只工作,但我的要求是查找MAC地址的WiFi是否开启与否。
这里是代码getMac地址不使用WiFi管理。
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" />
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);
}
}
文章来源: How to get the MAC address of an android device(WIFI is switched off) through code?