提交 1eedca85 编写于 作者: Z zhangchao

检视修改

Signed-off-by: Nzhangchao <zhangchao@kaihong.com>
上级 418ba6e2
...@@ -8,424 +8,434 @@ ...@@ -8,424 +8,434 @@
本例效果如下: 本例效果如下:
| 连接WIFI | WIFI列表 | | 扫描WLAN | 连接WLAN | 断开WLAN |
| :---------------------------------: | :----------------------------------: | | :----------------------------------------------------------: | :----------------------------------------------------------: | :----------------------------------------------------------: |
| ![contactlist](figures/connect.png) | ![contactlist](figures/wlanmain.png) | | <img src="figures/wlanscan.jpg" alt="contactlist" style="zoom: 50%;" /> | <img src="figures/wlanconnect.jpg" alt="contactlist" style="zoom: 50%;" /> | <img src="figures/wlandisconnect.jpg" alt="contactlist" style="zoom: 50%;" /> |
## 运行环境 ## 运行环境
本例基于以下环境开发,开发者也可以基于其他适配的版本进行开发。
- IDE:DevEco Studio 4.0.0.201 Beta1 - IDE:DevEco Studio 4.0.0.201 Beta1
- SDK:Ohos_sdk_public 4.0.7.5 (API Version 10 Beta1) - SDK:Ohos_sdk_public 4.0.7.5 (API Version 10 Beta1)
## 实现思路 ## 实现思路
本例主要通过@ohos.wifiManager 相关API实现wlan激活和关闭、扫描和连接WIFI等功能。 本例主要通过@ohos.wifiManager 相关API实现WLAN激活和关闭、扫描和连接WLAN等功能。
- WLAN功能的激活和关闭:点击首页的切换按钮,如果是打开,使用wifi.enableWifi()开启wifi;如果是关闭,则使用wifi.disconnect()断开wifi, 然后使用wifi.disableWifi()关闭wifi - WLAN功能的激活和关闭:点击首页的切换按钮,如果是打开,使用wifi.enableWifi()开启WLAN功能;如果是关闭,则使用wifi.disconnect()断开WLAN功能, 然后使用wifi.disableWifi()关闭WLAN。
- WIFI的连接:点击wifi列表中加密的wifi,并在弹窗中输入密码后,会在AvailableWifi.ets中通过WifiModule.connectNetwork()调用wifi.connectToDevice()连接wifi - WLAN的连接:点击WLAN列表中加密的WLAN,并在弹窗中输入密码后,会在AvailableWifi.ets中通过WifiModule.connectNetwork()调用wifi.connectToDevice()连接WLAN。
- WIFI的扫描:进入Index.ets 后就会间歇性的调用wifi.scan()开启扫描,然后通过WifiModel模块中的getScanInfos()调用wifi.getScanResults()来获取扫描的结果 - WLAN的扫描:进入Index.ets 后就会间歇性的调用wifi.scan()开启扫描,然后通过WifiModel模块中的getScanInfos()调用wifi.getScanResults()来获取扫描的结果.
## 开发步骤 ## 开发步骤
1.申请所需权限 1. 申请所需权限
​ 在model.json5中添加以下配置: 在model.json5中添加以下配置:
```json ```json
"requestPermissions": [ "requestPermissions": [
{ {
"name": "ohos.permission.GET_WIFI_INFO"//允许应用获取WLAN信息 "name": "ohos.permission.GET_WIFI_INFO"//允许应用获取WLAN信息
}, },
{ {
"name": "ohos.permission.GET_WIFI_INFO_INTERNAL"//允许应用获取WLAN信息 "name": "ohos.permission.GET_WIFI_INFO_INTERNAL"//允许应用获取WLAN信息
}, },
{ {
"name": "ohos.permission.SET_WIFI_INFO"//允许应用配置WLAN设备 "name": "ohos.permission.SET_WIFI_INFO"//允许应用配置WLAN设备
}, },
{ {
"name": "ohos.permission.GET_WIFI_PEERS_MAC"//允许应用获取对端WLAN或者蓝牙设备的MAC地址 "name": "ohos.permission.GET_WIFI_PEERS_MAC"//允许应用获取对端WLAN或者蓝牙设备的MAC地址
}, },
{ {
"name": "ohos.permission.GET_WIFI_LOCAL_MAC"//允许应用获取本机WLAN或者蓝牙设备的MAC地址 "name": "ohos.permission.GET_WIFI_LOCAL_MAC"//允许应用获取本机WLAN或者蓝牙设备的MAC地址
}, },
{ {
"name": "ohos.permission.GET_WIFI_CONFIG"//允许应用获取WLAN配置信息 "name": "ohos.permission.GET_WIFI_CONFIG"//允许应用获取WLAN配置信息
}, },
{ {
"name": "ohos.permission.SET_WIFI_CONFIG"//允许应用配置WLAN信息 "name": "ohos.permission.SET_WIFI_CONFIG"//允许应用配置WLAN信息
}, },
{ {
"name": "ohos.permission.MANAGE_WIFI_CONNECTION"//允许应用管理WLAN连接 "name": "ohos.permission.MANAGE_WIFI_CONNECTION"//允许应用管理WLAN连接
}, },
{ {
"name": "ohos.permission.MANAGE_WIFI_HOTSPOT"//允许应用开启或者关闭WLAN热点 "name": "ohos.permission.MANAGE_WIFI_HOTSPOT"//允许应用开启或者关闭WLAN热点
}, },
{ {
"name": "ohos.permission.LOCATION"//允许应用获取设备位置信息 "name": "ohos.permission.LOCATION"//允许应用获取设备位置信息
}, },
{ {
"name": "ohos.permission.APPROXIMATELY_LOCATION"//允许应用获取设备模糊位置信息 "name": "ohos.permission.APPROXIMATELY_LOCATION"//允许应用获取设备模糊位置信息
} }
] ]
``` ```
2.准备工作 2. 准备工作
```typescript 定义boolean变量isSwitchOn作为WLAN开关是否打开的标志。
import wifi from '@ohos.wifiManager'
aboutToAppear() { ```typescript
// 如果wifi是开的,就记录下状态,然后扫描wifi,并获取连接信息 import wifi from '@ohos.wifiManager'
if (wifi.isWifiActive()) {//查询wifi是否已使能 aboutToAppear() {
Logger.log(TAG, 'wifi is active') // 如果WLAN是开的,就记录下状态,然后扫描WLAN,并获取连接信息
this.isSwitchOn = true//已使能说明wifi开关已被打开,那么让isSwitchOn为true if (wifi.isWifiActive()) {//查询WLAN是否已使能
wifi.scan()//@ohos.wifiManager的接口,对wifi进行扫描 Logger.log(TAG, 'wifi is active')
this.scan()//自定义的scan函数,确保扫描的持续性 this.isSwitchOn = true//已使能说明WLAN开关已被打开,那么让isSwitchOn为true
this.getLinkedInfo() wifi.scan()//@ohos.wifiManager的接口,对WLAN进行扫描
} this.scan()//自定义的scan函数,确保扫描的持续性
// 启动监听 this.getLinkedInfo()
this.addListener()//监听连接状态的变化 }
} // 启动监听
``` this.addListener()//监听连接状态的变化
}
3.持续地扫描可用wifi ```
```typescript 3. 持续地扫描可用WLAN
async getLinkedInfo() {
try { scan方法不断地自我调用以实现对WLAN的不停扫描。
//调用getLinkedInfo接口得到是否已连接wifi的信息
let wifiLinkedInfo = await wifi.getLinkedInfo() ```typescript
if (wifiLinkedInfo === null || wifiLinkedInfo.bssid === '') { async getLinkedInfo() {
//如果结果为空,则说明未连接 try {
this.isLinked = false //调用getLinkedInfo接口得到是否已连接WLAN的信息
this.linkedInfo = null let wifiLinkedInfo = await wifi.getLinkedInfo()
return if (wifiLinkedInfo === null || wifiLinkedInfo.bssid === '') {
} //如果结果为空,则说明未连接
this.isLinked = true this.isLinked = false
this.linkedInfo = wifiLinkedInfo this.linkedInfo = null
} catch (err) { return
Logger.info(`getLinkedInfo failed err is ${JSON.stringify(err)}`) }
} this.isLinked = true
} this.linkedInfo = wifiLinkedInfo
async scan() { } catch (err) {
// 获取有关Wi-Fi连接的信息,存入linkedInfo Logger.info(`getLinkedInfo failed err is ${JSON.stringify(err)}`)
await this.getLinkedInfo() }
// 不停地扫描wifi }
let result: Array<WifiType> = await this.wifiModel.getScanInfos()//调用model/WifiModel.ets中的getScanInfos得到扫描结果 async scan() {
if (this.isSwitchOn) { // 获取有关WLAN连接的信息,存入linkedInfo
//如果wifi功能已打开,则要进行不停地扫描 await this.getLinkedInfo()
AppStorage.SetOrCreate('wifiList', result)//将扫描结果存至全局 // 不停地扫描WLAN
//每3000毫秒调用一次scan(),实现不停扫描可用wifi let result: Array<WifiType> = await this.wifiModel.getScanInfos()//调用model/WifiModel.ets中的getScanInfos得到扫描结果
setTimeout(async () => { if (this.isSwitchOn) {
await this.scan() //如果WLAN功能已打开,则要进行不停地扫描
}, 3000) AppStorage.SetOrCreate('wifiList', result)//将扫描结果存至全局
} //每3000毫秒调用一次scan(),实现不停扫描可用WLAN
} setTimeout(async () => {
addListener() { await this.scan()
// wifi连接状态改变事件发生时,修改连接信息 }, 3000)
wifi.on('wifiConnectionChange', async state => { }
Logger.log(TAG, `wifiConnectionChange: ${state}`) }
await this.getLinkedInfo()//wifi连接状态改变,重新获取wifi连接信息 addListener() {
}) // WLAN连接状态改变事件发生时,修改连接信息
// wifi状态改变时,先清空wifi列表,然后判断是否是开启状态,如果是就扫描 wifi.on('wifiConnectionChange', async state => {
wifi.on('wifiStateChange', state => { Logger.log(TAG, `wifiConnectionChange: ${state}`)
Logger.log(TAG, `wifiStateLisener state: ${state}`) await this.getLinkedInfo()//WLAN连接状态改变,重新获取WLAN连接信息
AppStorage.SetOrCreate('wifiList', []) })
if (state === 1) { // 1: wifi is enable, 0:wifi is disable // WLAN状态改变时,先清空WLAN列表,然后判断是否是开启状态,如果是就扫描
this.scan() wifi.on('wifiStateChange', state => {
} Logger.log(TAG, `wifiStateLisener state: ${state}`)
}) AppStorage.SetOrCreate('wifiList', [])
} if (state === 1) { // 1: wifi is enable, 0:wifi is disable
.................................... this.scan()
//model/WifiModel.ets }
async getScanInfos(): Promise<Array<WifiType>> { })
Logger.log(TAG, 'scanWifi begin') }
let wifiList: Array<WifiType> = [] ...
let result: Array<wifi.WifiScanInfo> = [] //model/WifiModel.ets
try { async getScanInfos(): Promise<Array<WifiType>> {
result = await wifi.getScanResults()//因为在abouttoappear()中执行了wifi.scan(),所以这里直接调用getScanResults接口得到扫描结果 Logger.log(TAG, 'scanWifi begin')
} catch (err) { let wifiList: Array<WifiType> = []
Logger.log(TAG, `scan info err: ${JSON.stringify(err)}`) let result: Array<wifi.WifiScanInfo> = []
return wifiList try {
} result = await wifi.getScanResults()//因为在abouttoappear()中执行了wifi.scan(),所以这里直接调用getScanResults接口得到扫描结果
Logger.log(TAG, `scan info call back: ${result.length}`) } catch (err) {
for (var i = 0; i < result.length; ++i) { Logger.log(TAG, `scan info err: ${JSON.stringify(err)}`)
wifiList.push({ return wifiList
ssid: result[i].ssid, }
bssid: result[i].bssid, Logger.log(TAG, `scan info call back: ${result.length}`)
securityType: result[i].securityType, for (var i = 0; i < result.length; ++i) {
rssi: result[i].rssi, wifiList.push({
band: result[i].band, ssid: result[i].ssid,
frequency: result[i].frequency, bssid: result[i].bssid,
timestamp: result[i].timestamp securityType: result[i].securityType,
}) rssi: result[i].rssi,
} band: result[i].band,
return wifiList frequency: result[i].frequency,
} timestamp: result[i].timestamp
``` })
}
4.构建UI框架、通过关闭按钮实现断开wifi连接。 return wifiList
}
```typescript ```
build() {
Column() { 4. 构建UI框架、通过关闭按钮实现断开WLAN连接。
TitleBar()//引入自component/TitleBar.ets,负责标题框的具体呈现
Row() { TitleBar组件呈现了标题框。WLAN开关按钮由一个Toggle组件呈现,其绑定的onChange事件在按钮被打开时开始扫描可用WLAN,在被关闭时断开当前连接WLAN并且关闭WLAN功能。当前已连接的WLAN由两个Text组件分别显示其ssid与连接状态。
Text($r('app.string.wlan'))
.fontSize(22) ```typescript
.fontWeight(FontWeight.Bold) build() {
.height(40) Column() {
Column() { TitleBar()//引入自component/TitleBar.ets,负责标题框的具体呈现
Toggle({ type: ToggleType.Switch, isOn: this.isSwitchOn })//切换按钮 Row() {
.id('switch') Text($r('app.string.wlan'))
.onChange((isOn: boolean) => { .fontSize(22)
Logger.log(`LSQ: wifi swtich is: ${isOn}`) .fontWeight(FontWeight.Bold)
AppStorage.SetOrCreate('wifiList', []) .height(40)
try { Column() {
// 如果按钮被打开了,记录状态,打开网络,开始扫描可用wifi Toggle({ type: ToggleType.Switch, isOn: this.isSwitchOn })//切换按钮
if (isOn) { .id('switch')
this.isSwitchOn = true .onChange((isOn: boolean) => {
wifi.enableWifi()//使wifi功能可用 Logger.log(`LSQ: wifi swtich is: ${isOn}`)
return AppStorage.SetOrCreate('wifiList', [])
} else { try {
// 如果按钮被关闭了记录状态,断开网络禁用网络 // 如果按钮被打开了,记录状态,打开网络,开始扫描可用WLAN
this.isSwitchOn = false if (isOn) {
this.isLinked = false this.isSwitchOn = true
wifi.disconnect()//断开当前wifi连接 wifi.enableWifi()//使WLAN功能可用
wifi.disableWifi()//使wifi功能不可用 return
} } else {
} catch (error) { // 如果按钮被关闭了记录状态,断开网络禁用网络
Logger.error(TAG, `failed,code:${JSON.stringify(error.code)},message:${JSON.stringify(error.message)}`) this.isSwitchOn = false
} this.isLinked = false
}) wifi.disconnect()//断开当前WLAN连接
} wifi.disableWifi()//使WLAN功能不可用
} }
.width('100%') } catch (error) {
.padding({ left: 16, right: 16 }) Logger.error(TAG, `failed,code:${JSON.stringify(error.code)},message:${JSON.stringify(error.message)}`)
if (this.isLinked && this.isSwitchOn) { }
//如果当前按钮处于打开状态,且wifi是已连接状态 })
Column() { }
Text($r('app.string.connected')) }
.fontSize(22) .width('100%')
.width('100%') .padding({ left: 16, right: 16 })
Row() { if (this.isLinked && this.isSwitchOn) {
Text(this.linkedInfo.ssid)//展示当前已连接的wifi //如果当前按钮处于打开状态,且WLAN是已连接状态
.fontSize(20) Column() {
.fontColor(Color.Black) Text($r('app.string.connected'))
.layoutWeight(1) .fontSize(22)
Text($r('app.string.connected')) .width('100%')
.fontSize(18) Row() {
.fontColor(Color.Black) Text(this.linkedInfo.ssid)//展示当前已连接的WLAN
} .fontSize(20)
.width('100%') .fontColor(Color.Black)
.padding(10) .layoutWeight(1)
.margin({ left: 16, right: 16 }) Text($r('app.string.connected'))
.border({ radius: 15, color: Color.Gray, width: 1 }) .fontSize(18)
.backgroundColor(Color.White) .fontColor(Color.Black)
} }
.width('100%') .width('100%')
.padding({ left: 16, right: 16 }) .padding(10)
} .margin({ left: 16, right: 16 })
if (this.isSwitchOn) { .border({ radius: 15, color: Color.Gray, width: 1 })
//如果按钮处于打开状态,展示所有可用wifi .backgroundColor(Color.White)
AvailableWifi({ linkedInfo: this.linkedInfo })//AvailableWifi引入自component/AvailableWifi.ets }
} .width('100%')
} .padding({ left: 16, right: 16 })
.width('100%') }
.height('100%') if (this.isSwitchOn) {
.backgroundColor($r('app.color.index_bg')) //如果按钮处于打开状态,展示所有可用WLAN
} AvailableWifi({ linkedInfo: this.linkedInfo })//AvailableWifi引入自component/AvailableWifi.ets
``` }
}
5.展示可用wifi列表及wifi的连接。 .width('100%')
.height('100%')
```typescript .backgroundColor($r('app.color.index_bg'))
//component/AvailableWifi.ets }
build() { ```
List() {
ListItem() { 5. 展示可用WLAN列表及WLAN的连接。
Row() {
Text($r('app.string.available_wlan')) 使用List组件呈现可用WLAN列表,ListItem由一个呈现WLANssid的Text组件,一个表示其是否被加密的Text组件和一个展示其加密与否图像的Image组件组成。
.fontSize(22)
.layoutWeight(1) ```typescript
} //component/AvailableWifi.ets
.id('validWlan') build() {
.width('100%') List() {
} ListItem() {
//通过数据懒加载的方式从数据源中每次迭代一个可用wifi进行展示,可用列表被放置在滚动容器中,被划出可视区域外的资源会被回收 Row() {
LazyForEach(this.wifiDataResource, (item, index) => { Text($r('app.string.available_wlan'))
ListItem() { .fontSize(22)
WifiView({ wifi: item })//WifiView引入自Component/WifiView.ets,负责可用Wifi信息展示的具体实现 .layoutWeight(1)
} }
.id(`Wifi${index}`) .id('validWlan')
//对可用wifi点击时触发事件 .width('100%')
.onClick(() => { }
Logger.info(TAG, 'wifi click') //通过数据懒加载的方式从数据源中每次迭代一个可用WLAN进行展示,可用列表被放置在滚动容器中,被划出可视区域外的资源会被回收
this.scanInfo = item LazyForEach(this.wifiDataResource, (item, index) => {
if (this.linkedInfo !== null && item.ssid === this.linkedInfo.ssid) { ListItem() {
prompt.showToast({ message: 'this wifi is connected' })//如果当前已连接wifi并且点击的就是这个wifi,创建并显示文本提示框 WifiView({ wifi: item })//WifiView引入自Component/WifiView.ets,负责可用WLAN信息展示的具体实现
return }
} .id(`Wifi${index}`)
if (item.securityType === 0 || item.securityType === 1) { //对可用WLAN点击时触发事件
//如果点击的这个wifi的加密类型是无效加密类型或者开放加密类型,调用model/Wifimodel.ets中的connectNetwork方法连接此wifi .onClick(() => {
this.wifiModel.connectNetwork(item, '') Logger.info(TAG, 'wifi click')
return this.scanInfo = item
} if (this.linkedInfo !== null && item.ssid === this.linkedInfo.ssid) {
//如果点击的这个wifi的加密类型是其他加密类型,则需要输入密码,调用component/PswDialog.ets中的方法进行弹窗的生成 prompt.showToast({ message: 'this wifi is connected' })//如果当前已连接WLAN并且点击的就是这个WLAN,创建并显示文本提示框
this.pswDialogController.open() return
}) }
}, item => JSON.stringify(item)) if (item.securityType === 0 || item.securityType === 1) {
} //如果点击的这个WLAN的加密类型是无效加密类型或者开放加密类型,调用model/Wifimodel.ets中的connectNetwork方法连接此WLAN
.width('100%') this.wifiModel.connectNetwork(item, '')
.height('100%') return
.padding({ left: 16, right: 16 }) }
.layoutWeight(1) //如果点击的这个WLAN的加密类型是其他加密类型,则需要输入密码,调用component/PswDialog.ets中的方法进行弹窗的生成
.divider({ strokeWidth: 1, color: Color.Gray, startMargin: 10, endMargin: 10 }) this.pswDialogController.open()
.margin({ top: 10 }) })
} }, item => JSON.stringify(item))
//pswDialogController回调的action函数,将传回的wifi信息与密码传入model/Wifimodel.ets中的connectNetwork方法中 }
onAccept(scanInfo, psw) { .width('100%')
Logger.info(TAG, 'connect wifi') .height('100%')
self.wifiModel.connectNetwork(scanInfo, psw) .padding({ left: 16, right: 16 })
} .layoutWeight(1)
.................................... .divider({ strokeWidth: 1, color: Color.Gray, startMargin: 10, endMargin: 10 })
//Component/WifiView.ets .margin({ top: 10 })
aboutToAppear() { }
Logger.debug(TAG, `aboutToAppear ${JSON.stringify(this.wifi)}`) //pswDialogController回调的action函数,将传回的WLAN信息与密码传入model/Wifimodel.ets中的connectNetwork方法中
if (this.wifi) { onAccept(scanInfo, psw) {
if (this.wifi.securityType) { Logger.info(TAG, 'connect wifi')
if (this.wifi.securityType === 0 || this.wifi.securityType === 1) { self.wifiModel.connectNetwork(scanInfo, psw)
//wifi的加密类型是无效加密类型或者开放加密类型 }
this.securityString = $r('app.string.open') ...
this.isLock = false //Component/WifiView.ets
} aboutToAppear() {
} Logger.debug(TAG, `aboutToAppear ${JSON.stringify(this.wifi)}`)
} if (this.wifi) {
} if (this.wifi.securityType) {
build() { if (this.wifi.securityType === 0 || this.wifi.securityType === 1) {
Row() { //WLAN的加密类型是无效加密类型或者开放加密类型
Column() { this.securityString = $r('app.string.open')
if (this.wifi) { this.isLock = false
if (this.wifi.ssid) { }
Text(this.wifi.ssid) }
.fontSize(20) }
.width('100%') }
} build() {
} Row() {
//如果wifi的加密类型是无效加密类型或者开放加密类型,显示“开放”,反之显示“加密” Column() {
Text(this.securityString) if (this.wifi) {
.fontSize(18) if (this.wifi.ssid) {
.fontColor(Color.Gray) Text(this.wifi.ssid)
.width('100%') .fontSize(20)
} .width('100%')
.layoutWeight(1) }
}
Stack({ alignContent: Alignment.BottomEnd }) { //如果WLAN的加密类型是无效加密类型或者开放加密类型,显示“开放”,反之显示“加密”
//如果wifi的加密类型是无效加密类型或者开放加密类型,显示不带锁的图标,反之显示带锁的图标 Text(this.securityString)
Image($r('app.media.wifi')) .fontSize(18)
.height(30) .fontColor(Color.Gray)
.width(30) .width('100%')
.objectFit(ImageFit.Contain) }
if (this.isLock) { .layoutWeight(1)
Image($r('app.media.lock'))
.objectFit(ImageFit.Contain) Stack({ alignContent: Alignment.BottomEnd }) {
.width(15) //如果WLAN的加密类型是无效加密类型或者开放加密类型,显示不带锁的图标,反之显示带锁的图标
.height(15) Image($r('app.media.wifi'))
} .height(30)
} .width(30)
.width(40) .objectFit(ImageFit.Contain)
.height(40) if (this.isLock) {
.margin({ right: 10 }) Image($r('app.media.lock'))
} .objectFit(ImageFit.Contain)
.backgroundColor(Color.White) .width(15)
.width('100%') .height(15)
.padding(10) }
} }
} .width(40)
.................................... .height(40)
//model/Wifimodel.ets .margin({ right: 10 })
connectNetwork(scanInfo: wifi.WifiScanInfo, psw) { }
prompt.showToast({ message: 'connecting', duration: 5000 }) .backgroundColor(Color.White)
Logger.debug(TAG, `connectNetwork bssid=${scanInfo.bssid}`) .width('100%')
// 这里因为api问题,需要声明为any,已提单 .padding(10)
let deviceConfig: any = { }
ssid: scanInfo.ssid, }
bssid: scanInfo.bssid, ...
preSharedKey: psw, //model/Wifimodel.ets
isHiddenSsid: false, connectNetwork(scanInfo: wifi.WifiScanInfo, psw) {
securityType: scanInfo.securityType prompt.showToast({ message: 'connecting', duration: 5000 })
} Logger.debug(TAG, `connectNetwork bssid=${scanInfo.bssid}`)
try { // 这里因为api问题,需要声明为any,已提单
wifi.connectToDevice(deviceConfig)//连接到指定网络 let deviceConfig: any = {
Logger.debug(TAG, `connectToDevice success`) ssid: scanInfo.ssid,
} catch (err) { bssid: scanInfo.bssid,
Logger.debug(TAG, `connectToDevice fail err is ${JSON.stringify(err)}`) preSharedKey: psw,
} isHiddenSsid: false,
try { securityType: scanInfo.securityType
wifi.addDeviceConfig(deviceConfig)//添加网络配置 }
} catch (err) { try {
Logger.debug(TAG, `addDeviceConfig fail err is ${JSON.stringify(err)}`) wifi.connectToDevice(deviceConfig)//连接到指定网络
} Logger.debug(TAG, `connectToDevice success`)
} } catch (err) {
.................................... Logger.debug(TAG, `connectToDevice fail err is ${JSON.stringify(err)}`)
//component/PswDialog.ets }
build() { try {
Column() { wifi.addDeviceConfig(deviceConfig)//添加网络配置
Text(this.scanInfo.ssid) } catch (err) {
.fontSize(20) Logger.debug(TAG, `addDeviceConfig fail err is ${JSON.stringify(err)}`)
.width('95%') }
}
TextInput({ placeholder: 'input password' })//密码的输入框 ...
.id('input') //component/PswDialog.ets
.type(InputType.Password) build() {
.placeholderColor(Color.Gray) Column() {
.fontSize(19) Text(this.scanInfo.ssid)
.margin({ top: 15 }) .fontSize(20)
.width('95%') .width('95%')
.height(36)
//每当输入框中的内容变化,它就赋值给psw TextInput({ placeholder: 'input password' })//密码的输入框
.onChange((value: string) => { .id('input')
this.psw = value .type(InputType.Password)
}) .placeholderColor(Color.Gray)
.fontSize(19)
Row() { .margin({ top: 15 })
//确认按钮 .width('95%')
Button() { .height(36)
Text($r('app.string.sure')) //每当输入框中的内容变化,它就赋值给psw
.fontColor(Color.Blue) .onChange((value: string) => {
.fontSize(17) this.psw = value
} })
.id('sure')
.layoutWeight(7) Row() {
.backgroundColor(Color.White) //确认按钮
.margin(5) Button() {
.onClick(() => { Text($r('app.string.sure'))
this.controller.close() .fontColor(Color.Blue)
this.action(this.scanInfo, this.psw) .fontSize(17)
}) }
.id('sure')
Text() .layoutWeight(7)
.width(1) .backgroundColor(Color.White)
.height(35) .margin(5)
.backgroundColor($r('app.color.text_color')) .onClick(() => {
//取消按钮 this.controller.close()
Button() { this.action(this.scanInfo, this.psw)
Text($r('app.string.cancel')) })
.fontColor(Color.Red)
.fontSize(17) Text()
} .width(1)
.layoutWeight(7) .height(35)
.backgroundColor(Color.White) .backgroundColor($r('app.color.text_color'))
.margin(5) //取消按钮
.onClick(() => { Button() {
this.controller.close() Text($r('app.string.cancel'))
}) .fontColor(Color.Red)
} .fontSize(17)
.width('100%') }
.margin({ top: '3%' }) .layoutWeight(7)
} .backgroundColor(Color.White)
.padding(15) .margin(5)
} .onClick(() => {
``` this.controller.close()
})
}
.width('100%')
.margin({ top: '3%' })
}
.padding(15)
}
```
## 全部代码 ## 全部代码
...@@ -433,5 +443,6 @@ connectNetwork(scanInfo: wifi.WifiScanInfo, psw) { ...@@ -433,5 +443,6 @@ connectNetwork(scanInfo: wifi.WifiScanInfo, psw) {
## 参考 ## 参考
[权限列表](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/security/permission-list.md#ohospermissiondistributed_datasync) - [权限列表](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/security/permission-list.md#ohospermissiondistributed_datasync)
- [@ohos.wifiManager](../application-dev/reference/apis/js-apis-wifiManager.md)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册