Implementation of the Bluetooth Connectivity Using .NET MAUI

Introduction

In this article, I will explain how you can use the .NET Multi-platform App UI (.NET MAUI) IConnectivity interface to inspect the network accessibility of the device. The network connection may have access to the internet. Devices also contain different kinds of network connections, such as Bluetooth cellular and WiFi. The IConnectivity interface has an event to monitor changes in the device's connection state. The default implementation of the IConnectivity interface is available through the Connectivity. Current property. Both the IConnectivity interface and Connectivity class are contained in Microsoft.Maui.Networking namespace.

Step 1. Create a new project in Visual Studio 2022 and select the app option under the multiplatform on the left side panel. After that, you need to click the .NET MAUI App with the C# option and click the continue button.

Add new project

Step 2. On the next page, you need to select the .Net framework version 6.0 and click the continue button.

Configure project

Step 3. On the next page, You need to provide your project name and solution name along with your location and click on the Create button

Preview project

Step 4. The next step is to define the permission in \Platforms\Android\AndroidManifest.xml file and The Android Manifest is an XML file that contains important metadata about the Android app. This includes the package name, activity names, and main activity. Android version support and hardware features support and permissions and other configurations.

Therefore, the following.

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"  android:maxSdkVersion="30"/>
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />

Step 5. The next step is to add the following code in the \Platforms\Android\MainActivity.cs MainActivity.cs is typically the default activity that is launched when your app starts and It's a MAUI class that extends the AppCompatActivity class and overrides methods like onCreate() to define what happens when the activity is created.

using Android;
using Android.App;
using Android.Content.PM;
using Android.OS;
using AndroidX.Core.App;

namespace Bluetooth
{
    [Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
    public class MainActivity : MauiAppCompatActivity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            if (Build.VERSION.SdkInt > Android.OS.BuildVersionCodes.R && ActivityCompat.CheckSelfPermission(this, Manifest.Permission.BluetoothConnect) != Permission.Granted)
            {
                ActivityCompat.RequestPermissions(Microsoft.Maui.ApplicationModel.Platform.CurrentActivity, new string[] { Android.Manifest.Permission.BluetoothConnect }, 102);
            }

            if (Build.VERSION.SdkInt <= Android.OS.BuildVersionCodes.R && ActivityCompat.CheckSelfPermission(this, Manifest.Permission.Bluetooth) != Permission.Granted)
            {
                ActivityCompat.RequestPermissions(Microsoft.Maui.ApplicationModel.Platform.CurrentActivity, new string[] { Android.Manifest.Permission.Bluetooth }, 102);
            }
        }
    }
}

Step 6. The next step is to use the following code after requesting the permission and it works on all the Android versions.

Note. The bluetoothAdapter.Disable(); and bluetoothAdapter.Enable(); was deprecated in API level 33. It can't work on the emulator Api 33 but works on the physical Xiaomi device I tested whose Android version is Api 33. It's strange.

namespace Bluetooth
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void OnConnectionClicked(object sender, EventArgs e)
        {
#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
        }
    }
}

Output screen

Bluetooth

Bluetooth Connection Allow

Conclusion

Hopefully, this article has given you sufficient information for you to connect Bluetooth using the MAUI app and run the app on both Android/iOS. Feel free to leave a comment if you would like me to further elaborate on anything within this article.


Similar Articles