我是新的移动开发人员。我正在使用Nativescript。我想创建一个功能blooetooth,搜索设备并与设备连接。我尝试了这段代码:
Ts代码:
import { Component, OnInit, NgZone } from "@angular/core";
let ble = require("nativescript-bluetooth");
export class ItemsComponent implements OnInit {
log: string = "";
constructor(private zone: NgZone) { }
ngOnInit(): void {
}
startScanning() {
console.log(ble.startScanning)
ble.startScanning({
serviceUUIDs: [],
seconds: 5,
onDiscovered: (peripheral) => {
console.log('peripheral.name')
console.log(peripheral.name)
this.zone.run(() => {
this.updateLog(`Device Name: ${peripheral.name}`);
})
if (peripheral.name == "SWING") {
this.stopScanning();
this.updateLog(`Device Name: ${peripheral.name}`);
}
}
}).then(() => {
this.updateLog("scanning completed");
}, (err) => {
console.error(`Error on scanning: ${err}`);
})
}
stopScanning() {
ble.stopScanning().then(() => {
this.updateLog("Stopped");
})
}
updateLog(message) {
console.log(message);
this.log += `\n${message}`;
}
}
HTML代码:
<ActionBar title="My App" class="action-bar">
</ActionBar>
<StackLayout>
<Button class="btn btn-primary btn-active" id="appButton" text="Search Device" (tap)="startScanning()"></Button>
<TextView text="{{ log }}" style="height: 100%;background-color: #282a37;color: #fff;" editable="false"></TextView>
</StackLayout>
结果:
console.log(ble.startScanning)
> JS: Angular is running in the development mode. Call enableProdMode() to enable the production mode. JS: function (arg) {
> JS: return new Promise(function (resolve, reject) {
> JS: try {
> JS: if (!Bluetooth._isEnabled())...<omitted>...
> JS: }