package com.movesdk.extentions import android.annotation.SuppressLint import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothManager import android.bluetooth.BluetoothProfile import android.content.Context import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine private val btProfiles = listOf( BluetoothProfile.A2DP, BluetoothProfile.HEADSET, ) @SuppressLint("MissingPermission") suspend fun Context.getConnectedDevices(): List { val connectedDevices = mutableSetOf() val profileIterator = btProfiles.iterator() while (profileIterator.hasNext()) { val profile = profileIterator.next() connectedDevices.addAll( getConnectedDevices(profile), ) } val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager bluetoothManager?.getConnectedDevices(BluetoothProfile.GATT)?.let(connectedDevices::addAll) return connectedDevices.toList() } private suspend fun Context.getConnectedDevices(profile: Int): List = suspendCoroutine { continuation -> val adapter = getSystemService(BluetoothManager::class.java)?.adapter adapter?.getProfileProxy( this, object : BluetoothProfile.ServiceListener { override fun onServiceConnected( profile: Int, proxy: BluetoothProfile?, ) { continuation.resume(proxy?.connectedDevices ?: emptyList()) adapter.closeProfileProxy(profile, proxy) } override fun onServiceDisconnected(profile: Int) {} }, profile, ) ?: { continuation.resume(emptyList()) } }