Mon. Sep 16th, 2024

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_toggle_bluetooth"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toggle Bluetooth" />

<Button
android:id="@+id/btn_search_devices"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search Devices"
android:layout_marginTop="16dp" />

<ListView
android:id="@+id/device_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="16dp" />

</LinearLayout>
MainActivity.kt
package com.androindian.exbluetoth

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.widget.Button
import android.widget.ListView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

class MainActivity : AppCompatActivity() {

private lateinit var bluetoothAdapter: BluetoothAdapter
private lateinit var deviceListAdapter: DeviceListAdapter
private val discoveredDevices = mutableListOf<BluetoothDevice>()

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

bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
deviceListAdapter = DeviceListAdapter(this, discoveredDevices)

val listView: ListView = findViewById(R.id.device_list)
listView.adapter = deviceListAdapter

val btnBluetoothToggle: Button = findViewById(R.id.btn_toggle_bluetooth)
val btnSearchDevices: Button = findViewById(R.id.btn_search_devices)

btnBluetoothToggle.setOnClickListener {
toggleBluetooth()
}

btnSearchDevices.setOnClickListener {
searchDevices()
}

// Register for broadcasts when a device is discovered
val filter = IntentFilter(BluetoothDevice.ACTION_FOUND)
registerReceiver(receiver, filter)
}

private fun toggleBluetooth() {
if (bluetoothAdapter.isEnabled) {
bluetoothAdapter.disable()
Toast.makeText(this, "Bluetooth turned off", Toast.LENGTH_SHORT).show()
} else {
bluetoothAdapter.enable()
Toast.makeText(this, "Bluetooth turned on", Toast.LENGTH_SHORT).show()
}
}

private fun searchDevices() {
// Check for location permission
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= android.content.pm.PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 1)
} else {
// Start discovery
if (bluetoothAdapter.isDiscovering) {
bluetoothAdapter.cancelDiscovery()
}
bluetoothAdapter.startDiscovery()
Toast.makeText(this, "Searching for devices...", Toast.LENGTH_SHORT).show()
}
}

// Create a BroadcastReceiver for ACTION_FOUND
private val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val action: String = intent.action!!
if (BluetoothDevice.ACTION_FOUND == action) {
// Discovery has found a device. Get the BluetoothDevice object and its info from the Intent
val device: BluetoothDevice? = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
device?.let {
discoveredDevices.add(it)
deviceListAdapter.notifyDataSetChanged()
}
}
}
}

override fun onDestroy() {
super.onDestroy()
// Unregister the broadcast receiver when the activity is destroyed
unregisterReceiver(receiver)
}
}
DeviceListAdapter.kt
package com.androindian.exbluetoth

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.TextView
import android.bluetooth.BluetoothDevice

class DeviceListAdapter(context: Context, private val devices: List<BluetoothDevice>) :
ArrayAdapter<BluetoothDevice>(context, 0, devices) {

override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val view = convertView ?: LayoutInflater.from(context).inflate(android.R.layout.simple_list_item_2, parent, false)
val device = devices[position]
val deviceName = view.findViewById<TextView>(android.R.id.text1)
val deviceAddress = view.findViewById<TextView>(android.R.id.text2)
deviceName.text = device.name ?: "Unknown Device"
deviceAddress.text = device.address
return view
}
}

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 *