1+ package com.example.testing_application
2+
3+ import android.annotation.SuppressLint
4+ import android.bluetooth.BluetoothManager
5+ import android.content.Context
6+ import android.content.IntentFilter
7+ import android.content.pm.PackageManager
8+ import kotlinx.coroutines.flow.MutableStateFlow
9+ import kotlinx.coroutines.flow.StateFlow
10+ import kotlinx.coroutines.flow.asStateFlow
11+ import kotlinx.coroutines.flow.update
12+ import toBluetoothDeviceDomain
13+ import java.util.jar.Manifest
14+
15+ @SuppressLint(" MissingPermission" )
16+ class AndroidBluetoothController (
17+ private val context : Context
18+ ): BluetoothController{
19+
20+ private val bluetoothManager by lazy{
21+ context.getSystemService(BluetoothManager ::class .java)
22+ }
23+
24+ private val bluetoothAdapter by lazy{
25+ bluetoothManager?.adapter
26+ }
27+
28+ private val _scannedDevices = MutableStateFlow <List <BluetoothDeviceDomain >>(emptyList())
29+ override val scannedDevices: StateFlow <List <BluetoothDeviceDomain >>
30+ get() = _scannedDevices .asStateFlow()
31+
32+ private val _pairedDevices = MutableStateFlow <List <BluetoothDeviceDomain >>(emptyList())
33+ override val pairedDevices: StateFlow <List <BluetoothDeviceDomain >>
34+ get() = _pairedDevices .asStateFlow()
35+
36+ private val foundDeviceReceiver = FoundDeviceReceiver {
37+ device -> _scannedDevices .update { devices ->
38+ val newDevice = device.toBluetoothDeviceDomain()
39+ if (newDevice in devices) devices else devices + newDevice
40+ }
41+ }
42+
43+ init {
44+ updatePairedDevices()
45+ }
46+
47+ override fun startDiscovery () {
48+ if (! hasPermission(android.Manifest .permission.BLUETOOTH_SCAN )){
49+ println (' S' );
50+ return
51+ }
52+ println (' F' );
53+
54+ context.registerReceiver(
55+ foundDeviceReceiver,
56+ IntentFilter (android.bluetooth.BluetoothDevice .ACTION_FOUND )
57+ )
58+
59+ updatePairedDevices()
60+ bluetoothAdapter?.startDiscovery()
61+ }
62+
63+ override fun stopDiscovery () {
64+ if (! hasPermission(android.Manifest .permission.BLUETOOTH_CONNECT )){
65+ return
66+ }
67+
68+ bluetoothAdapter?.cancelDiscovery()
69+ }
70+
71+ override fun release () {
72+ context.unregisterReceiver(
73+ foundDeviceReceiver
74+ )
75+ }
76+
77+ fun getScannedDevices (): List <BluetoothDevice > {
78+ return _scannedDevices .value
79+ }
80+
81+
82+ private fun updatePairedDevices (){
83+ if (! hasPermission(android.Manifest .permission.BLUETOOTH_CONNECT )){
84+ return
85+ }
86+ bluetoothAdapter?.bondedDevices?.map{
87+ it.toBluetoothDeviceDomain() }
88+ ?.also { devices ->
89+ _pairedDevices .update { devices } }
90+ }
91+
92+ fun hasPermission (permission : String ): Boolean {
93+ return context.checkSelfPermission(permission) == PackageManager .PERMISSION_GRANTED
94+ }
95+ }
0 commit comments