Android Kotlin: How to enable and disable device bluetooth programmatically

This code demonstrates how to programmatically control Bluetooth on an Android device written in Kotlin. The code resides in the MainActivity.kt file and utilizes an XML layout file (activity_main.xml) to define the user interface. Additionally, the AndroidManifest.xml file specifies required permissions for the application.

Key functionalities of the code include:

  • Checking if the device supports Bluetooth.
  • Displaying the current Bluetooth status (enabled or disabled).
  • Enabling Bluetooth by prompting the user for confirmation.
  • Disabling Bluetooth programmatically (requires BLUETOOTH_ADMIN permission).

Explanation of the Code:

The MainActivity class handles user interaction and Bluetooth operations. It first retrieves the default Bluetooth adapter and checks for device compatibility. Based on the adapter's state, the text view displays either a "supported" or "not supported" message.

Three buttons are defined in the layout (activity_main.xml):

  • Status: Displays the current Bluetooth state (enabled/disabled) in the text view.
  • Enable: Attempts to enable Bluetooth by prompting the user for confirmation via an intent.
  • Disable: Disables Bluetooth directly if it's currently enabled (requires BLUETOOTH_ADMIN permission).

The btnStatus click listener retrieves the adapter state and updates the text view accordingly.

The btnEnable click listener checks if Bluetooth is disabled. If so, it creates an intent with the ACTION_REQUEST_ENABLE action and starts an activity for the user to confirm enabling Bluetooth.

The btnDisable click listener checks if Bluetooth is enabled. If so, it directly calls the disable() method on the adapter to turn it off.

AndroidManifest.xml:

The manifest file declares two permissions required for the application:

  • BLUETOOTH: Allows the app to access Bluetooth functionalities.
  • BLUETOOTH_ADMIN: Grants permission for advanced operations like disabling Bluetooth (needed for the btnDisable functionality).

MainActivity.kt

package com.example.jetpack

import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

    private val REQUEST_ENABLE_BT = 1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // get device default bluetooth adapter
        val adapter = BluetoothAdapter.getDefaultAdapter()

        // check device support bluetooth or not
        if (adapter != null){
            textView.text = "Device support Bluetooth."
        }else{
            textView.text = "Device does not support Bluetooth."
        }


        // get bluetooth enable disable status
        btnStatus.setOnClickListener {
            adapter?.apply {
                textView.text = if (isEnabled){
                    "Bluetooth is enable."
                }else{
                    "Bluetooth is disable."
                }
            }
        }


        // enable bluetooth programmatically
        btnEnable.setOnClickListener {
            adapter?.apply {
                if (!isEnabled){
                    val intent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
                    startActivityForResult(intent, REQUEST_ENABLE_BT)
                }else{
                    textView.text = "Bluetooth is already enable."
                }
            }
        }


        // disable bluetooth programmatically
        btnDisable.setOnClickListener {
            adapter?.apply {
                if (isEnabled){
                    disable()
                }else{
                    textView.text = "Bluetooth is already disable."
                }
            }
        }
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#E5E4E2"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnStatus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:backgroundTint="#36747D"
        android:text="Status"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnDisable"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:backgroundTint="#C32148"
        android:text="Disable"
        app:layout_constraintBottom_toBottomOf="@+id/btnEnable"
        app:layout_constraintStart_toEndOf="@+id/btnEnable" />

    <Button
        android:id="@+id/btnEnable"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:backgroundTint="#545AA7"
        android:text="Enable"
        app:layout_constraintBottom_toBottomOf="@+id/btnStatus"
        app:layout_constraintStart_toEndOf="@+id/btnStatus" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="32dp"
        android:layout_marginEnd="16dp"
        android:fontFamily="sans-serif-condensed"
        android:gravity="center"
        android:textColor="#191970"
        android:textSize="30sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnStatus"
        tools:text="TextView" />

</androidx.constraintlayout.widget.ConstraintLayout>
AndroidMenifest.xml [permissions]

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
More android kotlin tutorials