Example #1
0
        public static async Task <BluetoothState> GetBluetoothState(Action callbackAction)
        {
            BluetoothStateBroadcastReceiver bluetoothStateBroadcastReceiver = new BluetoothStateBroadcastReceiver();

            bluetoothStateBroadcastReceiver.OnBluetoothStateChange += callbackAction;

            CrossCurrentActivity.Current.AppContext.RegisterReceiver(bluetoothStateBroadcastReceiver,
                                                                     new IntentFilter("android.bluetooth.adapter.action.STATE_CHANGED"));

            const int timeoutMs        = 2000;
            CancellationTokenSource ct = new CancellationTokenSource(timeoutMs);

            ct.Token.Register(() =>
            {
                bluetoothStateBroadcastReceiver._isBluetoothOnAsync?.TrySetResult(
                    BluetoothAdapter.DefaultAdapter != null && BluetoothAdapter.DefaultAdapter.IsEnabled);
                bluetoothStateBroadcastReceiver.OnBluetoothStateChange?.Invoke();
            }, false);

            BluetoothState bluetoothStateAsync;

            if (BluetoothAdapter.DefaultAdapter == null)
            {
                bluetoothStateAsync = BluetoothState.NO_ADAPTER;
            }

            bluetoothStateAsync = await bluetoothStateBroadcastReceiver.GetBluetoothStateAsync()
                ? BluetoothState.ON
                : BluetoothState.OFF;

            CrossCurrentActivity.Current.AppContext.UnregisterReceiver(bluetoothStateBroadcastReceiver);

            return(bluetoothStateAsync);
        }
Example #2
0
        public override async void OnReceive(Context context, Intent intent)
        {
            IsFlightModeOn = intent.GetBooleanExtra("state", false);
            // Wait until BT will be turned on or off
            await BluetoothStateBroadcastReceiver.GetBluetoothState(OnFlightModeChange);

            OnFlightModeChange?.Invoke();
        }