Search code examples
c#xamarinxamarin.iosxamarin.android

Prompt User to enable bluetooth in Xamarin Forms


Are there any workaround which I can use to prompt a user to enable bluetooth in Xamarin Forms / C#?

Like a Display Alert with 'Yes' or 'No' for prompting the user to switch on the bluetooth in case its not enabled.

If the user selects, 'Yes', the bluetooth is enabled.

Please help me to achieve this in both Android and iOS ! Thanks in advance.


Solution

  • iOS

    On iOS you can not change bluetooth programmatically without using private API's (which Apple does not allow in the App Store), the most you can do is redirect the user to the Bluetooth Settings with this code (note that it only works on a real device):

    // Is bluetooth enabled?
    var bluetoothManager = new CoreBluetooth.CBCentralManager();
    if (bluetoothManager.State == CBCentralManagerState.PoweredOff) {
        // Does not go directly to bluetooth on every OS version though, but opens the Settings on most
        UIApplication.SharedApplication.OpenUrl(new NSUrl("App-Prefs:root=Bluetooth")); 
    }
    

    Be aware that this method will prevent your app from getting App Store approval, since 'App-Prefs:root' is also considered a private API with this explanation: (thanks to @chucky for mentioning that)

    Your app uses the "prefs:root=" non-public URL scheme, which is a private entity. The use of non-public APIs is not permitted on the App Store because it can lead to a poor user experience should these APIs change.

    So for iOS there is no possibility without risk for app rejection.

    Android

    Android.Bluetooth.BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
    // is bluetooth enabled?
    bluetoothAdapter.IsEnabled;
    
    bluetoothAdapter.Disable();
    // or
    bluetoothAdapter.Enable();
    

    The BLUETOOTH and BLUETOOTH_ADMIN permission are required for this method to work.