Wed. Jan 15th, 2025

Here’s a simple Kotlin program to toggle Bluetooth on/off, search for nearby Bluetooth devices, and list the available devices. This is done in an Android environment using Kotlin

AndroidManifest.xml

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<Button
android:id="@+id/btn_turn_on"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Turn Bluetooth On" />

<Button
android:id="@+id/btn_turn_off"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Turn Bluetooth Off" />

<ListView
android:id="@+id/device_list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
MainActivity.kt
package com.androindian.bluetoothex

import android.Manifest
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.ListView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

class MainActivity : Activity() {

private val bluetoothAdapter: BluetoothAdapter? by lazy {
BluetoothAdapter.getDefaultAdapter()
}
private val REQUEST_ENABLE_BT = 1
private val REQUEST_LOCATION_PERMISSION = 2
private lateinit var deviceListAdapter: ArrayAdapter<String>
private val discoveredDevices = mutableListOf<String>()

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

val listView: ListView = findViewById(R.id.device_list)
val btnTurnOn: Button = findViewById(R.id.btn_turn_on)
val btnTurnOff: Button = findViewById(R.id.btn_turn_off)

deviceListAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, discoveredDevices)
listView.adapter = deviceListAdapter

checkBluetoothSupport()

// Request location permission (required for device discovery)
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
REQUEST_LOCATION_PERMISSION
)
}

// Enable Bluetooth
btnTurnOn.setOnClickListener {
if (bluetoothAdapter?.isEnabled == false) {
val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
} else {
Toast.makeText(this, "Bluetooth is already ON", Toast.LENGTH_SHORT).show()
}
}

// Disable Bluetooth
btnTurnOff.setOnClickListener {
if (bluetoothAdapter?.isEnabled == true) {
bluetoothAdapter?.disable()
Toast.makeText(this, "Bluetooth turned OFF", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Bluetooth is already OFF", Toast.LENGTH_SHORT).show()
}
}

// Start device discovery
startDiscovery()
}

private fun checkBluetoothSupport() {
if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth not supported on this device", Toast.LENGTH_SHORT).show()
finish()
}
}

private fun startDiscovery() {
bluetoothAdapter?.let {
if (it.isDiscovering) {
it.cancelDiscovery()
}
if (it.startDiscovery()) {
Toast.makeText(this, "Starting discovery...", Toast.LENGTH_SHORT).show()
registerReceiver(
BluetoothBroadcastReceiver { device ->
runOnUiThread {
discoveredDevices.add("${device.name} (${device.address})")
deviceListAdapter.notifyDataSetChanged()
}
},
BluetoothBroadcastReceiver.getIntentFilter()
)
} else {
Toast.makeText(this, "Failed to start discovery", Toast.LENGTH_SHORT).show()
}
}
}

override fun onDestroy() {
super.onDestroy()
bluetoothAdapter?.cancelDiscovery()
}
}



BluetoothBroadcastReceiver.kt
package com.androindian.bluetoothex

import android.bluetooth.BluetoothDevice
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter

class BluetoothBroadcastReceiver(private val onDeviceDiscovered: (BluetoothDevice) -> Unit) : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
when (intent?.action) {
BluetoothDevice.ACTION_FOUND -> {
val device: BluetoothDevice? = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
device?.let { onDeviceDiscovered(it) }
}
}
}

companion object {
fun getIntentFilter(): IntentFilter {
val filter = IntentFilter()
filter.addAction(BluetoothDevice.ACTION_FOUND)
return filter
}
}
}

By Rajashekar

I’m (Rajashekar) a core Android developer with complimenting skills as a web developer from India. I cherish taking up complex problems and turning them into beautiful interfaces. My love for decrypting the logic and structure of coding keeps me pushing towards writing elegant and proficient code, whether it is Android, PHP, Flutter or any other platforms. You would find me involved in cuisines, reading, travelling during my leisure hours.

Leave a Reply

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