참고

developer.android.com/guide/topics/connectivity/bluetooth?hl=ko

 

블루투스 개요  |  Android 개발자  |  Android Developers

The Android platform includes support for the Bluetooth network stack, which allows a device to wirelessly exchange data with other Bluetooth devices. The application framework provides access to the Bluetooth functionality through the Android Bluetooth…

developer.android.com

 

 

1. 권한 설정 

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<!-- If your app targets Android 9 or lower, you can declare ACCESS_COARSE_LOCATION instead. -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

 

 

2. 블루투스 지원되는지 확인  및 블루투스 활성화 

mBlueAdapter = BluetoothAdapter.getDefaultAdapter()

//check if bluetooth is available or not
if (mBlueAdapter == null) {
	showToast("bluetooth is not available")
    finish()
 } else {
 	mBlueAdapter?.let {
    	if (!it.isEnabled()) {
        	showToast("Turning On Bluetooth...")
        	//intent to on bluetooth
        	val intent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
        	startActivityForResult(intent, REQUEST_ENABLE_BT)
        } else {
       		 showToast("Bluetooth is already on")
        }
	}
}

 

 

 

 

 

3. 페어링된 기기 목록 

val pairedDevices: Set<BluetoothDevice>? = bluetoothAdapter?.bondedDevices
pairedDevices?.forEach { device ->
    val deviceName = device.name
    val deviceHardwareAddress = device.address // MAC address
}

 

 

4. 클라이언트로 연결  

private inner class ConnectThread(device: BluetoothDevice) : Thread() {
    private val mmSocket: BluetoothSocket? by lazy(LazyThreadSafetyMode.NONE) {
        device.createRfcommSocketToServiceRecord(MY_UUID)
    }

    public override fun run() {
        // Cancel discovery because it otherwise slows down the connection.
        bluetoothAdapter?.cancelDiscovery()
        mmSocket?.use { socket ->
            // Connect to the remote device through the socket. This call blocks
            // until it succeeds or throws an exception.
            socket.connect()
            // The connection attempt succeeded. Perform work associated with
            // the connection in a separate thread.
            manageMyConnectedSocket(socket)
        }
    }

    // Closes the client socket and causes the thread to finish.
    fun cancel() {
        try {
            mmSocket?.close()
        } catch (e: IOException) {
            Log.e(TAG, "Could not close the client socket", e)
        }
    }
}

 

+ Recent posts