@SuppressLint("MissingPermission")
class ScanPairedDevice(
private val context: Context,
) {
fun isSpecificDeviceConnected(): Boolean {
val adapter = context.getBlAdapter()
val pairedDevices: Set<BluetoothDevice>? = adapter?.bondedDevices
val myBl =
pairedDevices?.singleOrNull() { it.address == Const.blMac }
myBl?.let {
Const.blDevice = it
Const.blSocket =
if (Const.blSocket != null) {
Const.blSocket
} else {
it::class.java.getMethod(
"createRfcommSocket",
*arrayOf<Class<*>?>(Int::class.javaPrimitiveType)
).invoke(it, 1) as BluetoothSocket
}
}
return myBl != null
}
inner class Reconnect(
private val successHandler: Handler,
private val failHandler: Handler
) : Thread() {
override fun run() {
try {
Const.blSocket?.let {
it.connect()
}
} catch (e: Exception) {
e.printStackTrace()
val ms = failHandler.obtainMessage()
ms.obj = "블루투스와 연결이 불가합니다."
ms.sendToTarget()
return
}
val ms = successHandler.obtainMessage()
ms.sendToTarget()
}
}
}
binding.buttonHomeStart.setOnClickListener {
if (adapter?.isEnabled == false) {
} else if (!ScanPairedDevice(requireContext()).isSpecificDeviceConnected()) {
} else {
if (Const.blSocket?.isConnected == true) {
}else {
ScanPairedDevice(requireContext()).Reconnect(
object : Handler(Looper.getMainLooper()) {
override fun handleMessage(msg: Message) {
super.handleMessage(msg)
Timber.d("goToStartFragment - thread")
}
},
object : Handler(Looper.getMainLooper()){
override fun handleMessage(msg: Message) {
super.handleMessage(msg)
Timber.d("goToStartFragment - toast")
val toastMessage = msg.obj.toString()
Toast.makeText(requireContext(),toastMessage, Toast.LENGTH_SHORT).show()
}
}
).start()
}
}
}