티스토리 뷰

 

[MainActivity]

val deviceAddress = "00:00:00:00:00:00" // Replace with the address of your Bluetooth device
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)
    }
    
    // Get the Bluetooth device by its address
    val device: BluetoothDevice = bluetoothAdapter.getRemoteDevice(deviceAddress)
    
    // Create a Bluetooth socket
    val socket: BluetoothSocket = device.createRfcommSocketToServiceRecord(MY_UUID)
    
    // Connect to the device
    try {
        socket.connect()
        // Connection successful, do something with the socket
    } catch (e: IOException) {
        // Connection failed, handle the error
    }
}

 

 

반응형