开发前需要在module.json5文件中的requestPermissions字段添加{"name": "ohos.permission.GET_WIFI_INFO"}申请权限,当macType是1时,获取macAddress还需申请ohos.permission.GET_WIFI_LOCAL_MAC权限。
使用Promise异步回调,通过macAddress属性获取MAC地址信息。
import wifiManager from '@ohos.wifiManager';
@Entry
@Component
struct Index {
build() {
Column() {
Button("点击获取当前连接的Wi-Fi信息")
.onClick(() => {
wifiManager.getLinkedInfo().then(data => {
console.info(`get wifi linked info: ${JSON.stringify(data.macAddress)}`);
}).catch((error: Error) => {
console.error(`get linked failed: ${JSON.stringify(error)}`);
});
})
}
}
} 成功获取到WLAN随机MAC,输出结果如下:
