BLE扫描功能在离子v4应用程序中无法正常工作

时间:2019-04-05 07:28:30

标签: android ionic-framework bluetooth bluetooth-lowenergy ionic4

我使用 ionic框架v4 创建了一个小型应用。

我安装了 cordova-plugin-ble-central ,并使用 scan()功能扫描了所有设备,但没有找到所有设备。例如,我正在尝试扫描Samsung Galaxy S6,但找不到。

移动矿机是三星Galaxy S8

我在 home.page.ts 中的代码:

import { Component, NgZone } from "@angular/core";
import { BLE } from "@ionic-native/ble/ngx";
import { AlertController, ToastController } from "@ionic/angular";

@Component({
  selector: "app-home",
  templateUrl: "home.page.html",
  styleUrls: ["home.page.scss"]
})
export class HomePage {
  devices: any[] = [];
  statusMessage: string;

  constructor(
    private ble: BLE,
    private alertCtrl: AlertController,
    private toastCtrl: ToastController,
    private ngZone: NgZone
  ) {
    this.checkBluetooth();
  }

  checkBluetooth() {
    this.ble.isEnabled().then(
      success => {
        this.showToast("Bluetooth is enabled");
      },
      error => {
        this.showError("Bluetooth is *not* enabled");
      }
    );
  }

  enableBluetooth() {
    this.ble.enable().then(
      success => {
        this.showToast("Bluetooth is enabled");
      },
      error => {
        this.showError("The user did *not* enable Bluetooth");
      }
    );
  }

  listDevices() {
    this.setStatus("Scanning for bluetooth LE devices");
    this.devices = [];

    this.ble
      .scan([], 5)
      .subscribe(
        device => this.onDeviceDiscovered(device),
        error => this.showError("No devices because " + error)
      );
    setTimeout(this.setStatus.bind(this), 5000, "Scan complete");
  }

  onDeviceDiscovered(device) {
    this.showToast("Discovered " + JSON.stringify(device, null, 2));
    this.ngZone.run(() => {
      this.devices.push(device);
    });
  }

  setStatus(message) {
    this.showToast(message);
    this.ngZone.run(() => {
      this.statusMessage = message;
    });
  }

  async showError(error) {
    const alert = await this.alertCtrl.create({
      header: "Error",
      subHeader: error,
      buttons: ["OK"]
    });
    await alert.present();
  }

  async showToast(msj) {
    const toast = await this.toastCtrl.create({
      message: msj,
      duration: 1000
    });
    await toast.present();
  }
}

interface pairedlist {
  class: number;
  id: string;
  address: string;
  name: string;
}

如何进行扫描才能正确找到所有设备?谢谢。

0 个答案:

没有答案