问题
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();
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.
回答1:
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" />
回答2:
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);
}
}
来源:https://stackoverflow.com/questions/14190602/how-to-get-the-mac-address-of-an-android-devicewifi-is-switched-off-through-co