Turn Bluetooth On/Off in Android Studio

Welcome. Here in this tutorial, you will learn how to Turn Bluetooth On/Off in Android Studio

Turning Bluetooth On/Off Example for Android Studio

Bluetooth is a protocol, which enables gadgets to interface remotely to trade the information with other Bluetooth gadgets.
For the most part, in android applications by utilizing Bluetooth API’s we can actualize Bluetooth functionalities, for example, empower or debilitate a Bluetooth, looking for accessible Bluetooth gadgets, associating with the gadgets and dealing with the information move between gadgets inside the range. We will have to use the BluetoothAdapter class to deal with Bluetooth in Android Studio.

Enabling or Turning On Bluetooth in Android Studio

To turn On Bluetooth, you will have to use startActivityForResult() method and ACTION_REQUEST_ENABLE intent with BluetoothAdapter to request for permission to turn on Bluetooth in your android app. The code is shown below for example:

Disbling or Turning Off Bluetooth in Android Studio

You can turn off Bluetooth by using disable() method from BluetoothAdapter in Android Studio. The code snippet is shown below:-

Note:- You will also need to add permission in AndroidManifest.xml file for any Bluetooth related work. Simply open the xml file and add this line:-

A sample image button is shown in the below picture. The button when switched will turn On Bluetooth or turn it Off as the case may be.

The Full Java Code along with the XML layout for creating app like the above example is shown below:-

  • First Create a new project in Android Studio
  • File ⇒ New Android ⇒ Application Project
  • Then Open src -> package -> MainActivity.java and then add following code :

JAVA (MainActivity.java)

The code for the MainActivity.java is given below

  •  Now Open res -> layout -> activity_main.xml and then add following code :

XML (activity_main.xml)

The content_main.xml is given below:

 

You can directly copy paste these snippets to your android studio, and they should work perfectly. Just save and run your project. You can also try to play with these other Bluetooth settings on your own and see the corresponding changes accordingly. There are a variety of properties available which can be changed as per your requirements.

Output:

Finally, run this project.

This is how Android Count Down Timer Code look like.

Turn Bluetooth On/Off in Android Studio Turn Bluetooth On/Off in Android Studio Turn Bluetooth On/Off in Android Studio

For a more detailed guide, you can also visit android’s official guide below:-

https://developer.android.com/guide/topics/connectivity/bluetooth

Comment down below if you are facing any problems.

Also Read:-

Leave a Reply

Your email address will not be published. Required fields are marked *