离子 - 如何检查蓝牙状态变化

时间:2016-05-25 01:50:45

标签: cordova bluetooth ionic-framework

目前,我正在使用cordova.plugins.diagnostic检查蓝牙当前是开启还是关闭。如果蓝牙处于关闭状态,则会提示用户将其打开并且“继续按钮”被禁用。在它已经打开之后,如何检测它已经打开并启用“继续”按钮。

以下是如何检测蓝牙启用/禁用的代码:

cordova.plugins.diagnostic.isBluetoothEnabled(function(enabled){
    console.log("Bluetooth is " + (enabled ? "enabled" : "disabled"));
}, function(error){
    console.error("The following error occurred: "+error);
});

然后,这是如何检查对蓝牙状态所做的更改的代码:

$ionicPlatform.ready(function() {
     cordova.plugins.diagnostic.registerBluetoothStateChangeHandler(function(state ){

    if(state === cordova.plugins.diagnostic.bluetoothState.POWERED_ON){
        alert("Bluetooth is able to connect");
        $scope.bluetoothIsEnabled = true;
    }

    else if(state === cordova.plugins.diagnostic.bluetoothState.POWERED_OFF){
       alert("Bluetooth is Off");
       $scope.bluetoothIsEnabled = false;
   }
});

})

但是,如果我从关闭测试开启或开启开启关闭,则不会出现任何警报。好像处理程序没有回调。

1 个答案:

答案 0 :(得分:2)

cordova.plugins.diagnostic.isBluetoothEnabled(function(enabled){
    if (enabled) {
        // bluetooth already on
    } else {
        // bluetooth off
    }
}, function(error){
    console.error("The following error occurred: "+error);
});

cordova.plugins.diagnostic.setBluetoothState(function(){
    console.log("Bluetooth was enabled");
}, function(error){
    console.error("The following error occurred: "+error);
}, true);

html化妆

<button class="button" ng-disabled="!bluetoothIsEnabled" on-tap="yourFunction($event)"></button>

bluetooth state listen

cordova.plugins.diagnostic.registerBluetoothStateChangeHandler(function(state){
    // "unknown", "resetting", "unsupported", "unauthorized", "powered_off", "powered_on"
    if (state == "powered_on") {
        $scope.bluetoothIsEnabled = true;
    } else {
        $scope.bluetoothIsEnabled = false;
    }
});
相关问题