页面创建时扫描蓝牙,只有第一个能显示,后面的都不显示了。
import { ble, socket } from '@kit.ConnectivityKit';
import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit';
import BluetoothSocket from '../../common/bluetooth/BluetoothSocket';
import BluetoothUtil from '../../common/bluetooth/BluetoothUtil';
import BleScanManager from '../../common/bluetooth/BleScanManager';
import { abilityAccessCtrl, PermissionRequestResult } from '@kit.AbilityKit';
import { Datas } from '../../common/utils/Datas';
import Logger from '../../common/utils/Logger';
import { JSON } from '@kit.ArkTS';
/**
* 附近设备
*/
@Component
export struct VicinityLock{
atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
@State bleList:Array<ble.ScanResult> = []
bleNameArray:Array<string> = [];
build() {
//附近设备
Column(){
Row(){
Text()
.width(5)
.height(15)
.backgroundColor(Color.Green)
.borderRadius(2)
.margin({right:5})
Text('附近设备')
}.width('100%')
Column(){
this.LockList()
}
}.width('90%')
}
@Builder LockList(){
ForEach(this.bleList,(lock:ble.ScanResult) => {
Row(){
Image($r('app.media.hlzn_launcher'))
.width(70)
.height(70)
.margin({left:5})
Column({space:7}){
Row({space:95}){
Text(lock.deviceName)
Text($r('app.string.lock_on_line'))
.fontColor(Color.Green)
}
.width('100%')
.justifyContent(FlexAlign.Start)
}
.height(70)
.margin({left:20})
}
.borderColor(Color.White)
.backgroundColor(Color.White)
.width('100%')
.height(80)
.margin({bottom:5})
.borderRadius(5)
}, (lock:ble.ScanResult,index:number) => index.toString())
}
aboutToAppear(): void {
try {
let context = getContext(this);
this.atManager.requestPermissionsFromUser(context, ['ohos.permission.ACCESS_BLUETOOTH'], (err: BusinessError, data: PermissionRequestResult)=>{
console.info(`data: `+ JSON.stringify(data));
console.info(`data permissions:` + data.permissions);
console.info(`data authResults:` + data.authResults);
//开启扫描
BleScanManager.startScan();
//监听扫描结果
BleScanManager.onScanResult((bleResult:ble.ScanResult) => {
if(this.bleNameArray.indexOf(bleResult.deviceName) == -1){
this.bleList.push(bleResult);
}
this.bleNameArray.push(bleResult.deviceName)
Logger.p('bleResult===='+bleResult.deviceName)
Logger.p('bleResult===='+this.bleList.length)
});
});
} catch(err) {
console.log(`${JSON.stringify(err)}`);
}
}
}
@Extend(Text) function normal(){
.fontColor($r('app.color.text_color'))
.fontSize($r('app.float.normal_text_size'))
}
@Extend(Text) function small(){
.fontSize($r('app.float.small_text_size'))
.fontColor($r('app.color.text_color'))
}
可以尝试一下这样的foreach写法,示例如下: