참고
developer.android.com/guide/topics/connectivity/bluetooth?hl=ko
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)
}
}
}
'Android' 카테고리의 다른 글
[Android] Activity Result API 사용해보기 (0) | 2020.10.22 |
---|---|
[Android] EncryptedSharedPreferences 사용해보기 (0) | 2020.10.20 |
[Android] VewModel LiveData Unit Test (0) | 2020.10.12 |
[Android] Hilt 사용해보기 (0) | 2020.10.09 |
[Android] 권한 요청 (0) | 2020.10.05 |