Android: Update Bluetooth programmatically

One of the reasons I like working with android is that it gives flexibility to developers to tweak things and play around with features. Apple on the other hand is very restrictive. Android allows us to manage features like Bluetooth and wifi programmatically while in iOS, the user is directed to the settings section. The user has to turn the wifi/Bluetooth one or off manually.

Today we’ll look at how we can change the status of wifi and Bluetooth with code.

Android SDK provides us a BluetoothAdapter class to work with Bluetooth. With BluetoothAdapter we can monitor and update the status of this service.

Let's see how it's done in code.

The Bluetooth section will have an icon and a switch. We will change the icon colour depending on the Bluetooth state. If Bluetooth is on, the icon will be green and red when it is off. We can turn Bluetooth on and off using the switch. Here is a snippet with widgets wrapped in cardview.

Let’s see how we implement it in kotlin. In our activity, as soon as it is launched we have to check the status of the Bluetooth and update the UI accordingly.

One important thing here is we need to add permissions in the manifest to access Bluetooth

Hope you find it helpful.

HAPPY CODING!!!