In this first part of Bluetooth series examples for Android we are going to see how Bluetooth service is switched on and off on a device. For this example we are going to use actual device for testing, because there is more complicated to test it on emulator.

The first thing we need to do is to add ButterKnife library in to our project, that is strongly recommended so we can bind the views form our XML in to our java code. This is done in build.gradle file in app folder in our project

The next thing we need to do is add permissions in our AndroidManifest.xml file like:

Then we need to add Switch button so we can turn the Bluetooth on the device on and off:

Here is the Main Activity where in onCreate method we add our previously imported library ButterKnife with .bind() method. We must initialize the BluetoothAdapter class (default Bluetooth adapter class in Android) with BluetoothAdapter.getDefaultAdapter(); After that we check if the bswitch is ON or OFF to start the Bluetooth service or stop it. That is happening in BluetoothManager that we will see it later in this example.

And the end there is most important part of this example the actial turning on and off the bluetooth service on the device. In this example there are two ways of turning the Bluetooth, with system permission or without it. The first one is commented code, and do the same thing as the second one but with a pop up requesting users permission. These are public static methods, so we dont need to create an object from BluetoothManager class in our MainActivity.

The turnOn() method (with system permissions) accepts BluetoothAdapter and the Activity object as a parameters. They are passed from Main Activity where we have instantiated the BluetoothAdapter and it is passed here, and the Activity object is passed so we can create a Intent. After the intent is being created that calls for enabling the bloototh service to be active, we declare REQUEST code so we can start the activity for result. We are activating the call for the service with .enable() method on the bluetooth adapter.

For turnOn() method without permissions we use only .enable() method on the bluetooth adapter.

The turnOff() method is simpler. We just check if the bluetooth adapter is active, and if it is, we turn it off with .disable() method

Here are the string resources used in this project:

Spread the love

Leave a Reply

Your email address will not be published.