Ionic - 如何检查蓝牙状态变化
Posted
技术标签:
【中文标题】Ionic - 如何检查蓝牙状态变化【英文标题】:Ionic - How To Check Bluetooth State Change 【发布时间】:2016-05-25 01:50:45 【问题描述】:目前我正在使用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;
);
)
但是,如果我从 Off 到 On 或 On 到 Off 进行测试,则不会出现任何警报。似乎处理程序没有回调。
【问题讨论】:
【参考方案1】: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>
蓝牙状态监听
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;
);
【讨论】:
谢谢,您的意思是将cordova.plugins.diagnostic.setBluetoothState
放入“继续按钮”事件中?那么如何在蓝牙开启后启用该按钮?
使用ng-disabled
<button class="button" ng-disabled="!bluetoothIsEnabled" on-tap="yourFunction($event)"></button>
是的,我明白这一点,但该按钮将如何启用,而 bluetoothIsEnabled 为假。因为,从我的情况来看,我在蓝牙关闭之前提到过。用户启用蓝牙后,此cordova.plugins.diagnostic.isBluetoothEnabled
不会回调以将值bluetoothIsEnabled
更改为true。
对不起,我错过了registerBluetoothStateChangeHandler
功能,你可以用它来监听蓝牙状态。
谢谢,它成功了。但是安卓怎么样?因为这个事件只适用于ios。以上是关于Ionic - 如何检查蓝牙状态变化的主要内容,如果未能解决你的问题,请参考以下文章