-
Android
Set Bluetooth permissions in theAndroidManifest.xml
file. Enable the location permission on the Android device.1 2 3 4 5
<uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" /> <uses-permission android:name="android.permission.BLUETOOTH_SCAN" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> // Required for Bluetooth scanning
Use the
InTheHand.Bluetooth.Permissions
package to check permissions with the codevar state = await Permissions.RequestAsync<InTheHand.Bluetooth.Permissions.Bluetooth>();
.
Check if Bluetooth is enabled.1 2 3 4 5 6 7 8 9 10 11 12 13 14
#if ANDROID var bluetoothManager = (Android.Bluetooth.BluetoothManager)Android.App.Application.Context.GetSystemService(Android.Content.Context.BluetoothService); if (bluetoothManager != null) { var bluetoothAdapter = bluetoothManager.Adapter; if (bluetoothAdapter != null && bluetoothAdapter.IsEnabled == false) { bluetoothAdapter.Enable(); //var enable = new Android.Content.Intent(Android.Bluetooth.BluetoothAdapter.ActionRequestEnable); //enable.SetFlags(Android.Content.ActivityFlags.NewTask); //Android.App.Application.Context.StartActivity(enable); } } #endif
1 2 3 4 5 6 7 8 9 10 11 12
#if ANDROID var bluetoothManager = (Android.Bluetooth.BluetoothManager)Android.App.Application.Context.GetSystemService(Android.Content.Context.BluetoothService); var bluetoothAdapter = bluetoothManager.Adapter; if (bluetoothAdapter.IsEnabled == true) { bluetoothAdapter.Disable(); } else { bluetoothAdapter.Enable(); } #endif
You can use the following code after requesting the permission, and it works on all Android versions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#if ANDROID var enable = new Android.Content.Intent( Android.Bluetooth.BluetoothAdapter.ActionRequestEnable); enable.SetFlags(Android.Content.ActivityFlags.NewTask); var disable = new Android.Content.Intent( Android.Bluetooth.BluetoothAdapter.ActionRequestDiscoverable); disable.SetFlags(Android.Content.ActivityFlags.NewTask); var bluetoothManager = (Android.Bluetooth.BluetoothManager)Android.App.Application.Context.GetSystemService(Android.Content.Context.BluetoothService); var bluetoothAdapter = bluetoothManager.Adapter; if (bluetoothAdapter.IsEnabled == true) { Android.App.Application.Context.StartActivity(disable); // disable the bluetooth } else { // enable the bluetooth Android.App.Application.Context.StartActivity(enable); } #endif
-
Windows