在开发过程中,有时我们需要获取系统的一些硬件信息。在这里,介绍一些硬件信息的获取方法,其中包括BT mac, BLE mac,WIFI mac, WIFI DIRECT mac.
- BT mac
BT mac是指设备的蓝牙地址。获取方法如下:
BluetoothManager btManager = (BluetoothManager) getContext().getSystemService(Context.BLUETOOTH_SERVICE);BluetoothAdapter btAdapter = btManager.getAdapter();String btMac;//在6.0版本以后,获取硬件ID变得更加严格,所以通过设备的地址映射得到mac地址if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { btMac = android.provider.Settings.Secure.getString(getContext.getContentResolver(), "bluetooth_address");}else { btMac = btAdapter.getAddress();}
private String getBluetoothMacAddress() {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
String bluetoothMacAddress = "";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M){
try {
Field mServiceField = bluetoothAdapter.getClass().getDeclaredField("mService");
mServiceField.setAccessible(true);
Object btManagerService = mServiceField.get(bluetoothAdapter);
if (btManagerService != null) {
bluetoothMacAddress = (String) btManagerService.getClass().getMethod("getAddress").invoke(btManagerService);
}
} catch (NoSuchFieldException e) {
} catch (NoSuchMethodException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
} else {
bluetoothMacAddress = bluetoothAdapter.getAddress();
}
return bluetoothMacAddress;
}
- BLE mac
BLE mac是指设备的蓝牙低能耗模块的地址,一般来说,其值和BT mac相等。
- WIFI mac
WIFI mac是指设备进行wifi连接时的地址,获取方法如下:
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String wifiMac = wifiInfo.getMacAddress();
- WIFI DIRECT mac
WIFI DIRECT mac是指设备进行wifi直连时自身的地址,获取方法如下(由于android自身的api目前还没有直接获取的方法,所以使用java的api进行获取):
public String getWFDMacAddress(){
try {
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface ntwInterface : interfaces) {
if (ntwInterface.getName().equalsIgnoreCase("p2p0")) {
byte[] byteMac = ntwInterface.getHardwareAddress();
if (byteMac==null){
return null;
}
StringBuilder strBuilder = new StringBuilder();
for (int i=0; i<byteMac.length; i++) {
strBuilder.append(String.format("%02X:", byteMac[i]));
}
if (strBuilder.length()>0){
strBuilder.deleteCharAt(strBuilder.length()-1);
}
return strBuilder.toString();
}
}
} catch (Exception e) {
Log.d(TAG, e.getMessage());
}
return null;
}
参考:
How do you retrieve the WiFi Direct MAC address?--stackoverflow
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。