2016-05-25 42 views
0

目前我使用cordova.plugins.diagnostic來檢查藍牙當前是否處於開啓或關閉狀態。如果藍牙處於關閉狀態,則提示用戶將其打開並且「繼續按鈕」被禁用。在它已經打開之後,我如何檢測它已經打開,並使繼續按鈕啓用。Ionic - 如何檢查藍牙狀態變化

下面是一個代碼,如何檢測藍牙啓用/禁用:

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
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; 
    } 
}); 
+0

謝謝你,你通過把'cordova.plugins.diagnostic.setBluetoothState'在 「繼續按鈕」 事件呢?那麼如何讓藍牙開啓後啓用該按鈕? –

+0

使用'ng-disabled''' –

+0

yup,我明白,將啓用而bluetoothIsEnabled爲false。因爲,從我的情景我提到藍牙關閉之前。用戶啓用藍牙後,此'cordova.plugins.diagnostic.isBluetoothEnabled'不回調將值'bluetoothIsEnabled'更改爲true。 –