SWDesk/App
[Kotlin] Bluetooth Application in Android
inhae
2023. 2. 14. 18:18
[MainActivity]
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()
// Check if device supports Bluetooth
if (bluetoothAdapter == null) {
// Device does not support Bluetooth
} else {
// Device supports Bluetooth
// Check if Bluetooth is enabled on device
if (!bluetoothAdapter.isEnabled) {
// Request to enable Bluetooth
val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
}
// Start scanning for nearby Bluetooth devices
bluetoothAdapter.startDiscovery()
// Register for broadcast of discovered devices
val filter = IntentFilter(BluetoothDevice.ACTION_FOUND)
registerReceiver(receiver, filter)
}
// BroadcastReceiver to handle discovered devices
val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val action: String = intent.action
if (BluetoothDevice.ACTION_FOUND == action) {
val device: BluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
// Do something with discovered device
}
}
}
[AndroidManifest.xml]
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
반응형