티스토리 뷰

[MainActivity]

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import java.io.IOException
import java.util.*

val deviceAddress = "00:00:00:00:00:00" // Replace with the address of your nano33iot device
val uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB") // UUID for serial communication
var bluetoothSocket: BluetoothSocket? = null

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)
    
    // Connect to the device using a Bluetooth socket
    try {
        bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid)
        bluetoothSocket.connect()
    } catch (e: IOException) {
        // Connection failed
    }
    
    // Send the text "Hello" to the device
    val outputStream = bluetoothSocket.outputStream
    val bytes = "Hello".toByteArray()
    outputStream.write(bytes)
}

// Close the Bluetooth socket when finished
try {
    bluetoothSocket?.close()
} catch (e: IOException) {
    // Error occurred while closing the socket
}

 

반응형