fun Context.getBlAdapter(): BluetoothAdapter? {
val bm = this.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
return bm.adapter
}
@SuppressLint("MissingPermission")
class ScanBluetooth(
private val context: Context,
private val fm: FragmentManager,
private val scanFailedCallBack: (() -> Unit)
) {
private val mainThreadHandler = HandlerCompat.createAsync(Looper.getMainLooper())
private var receiver: BroadcastReceiver? = null
private val adapter by lazy { context.getBlAdapter() }
private val scanner = adapter?.bluetoothLeScanner
fun scanDevices() {
if (adapter?.isEnabled == false) return
setReceiver()
adapter?.cancelDiscovery()
mainThreadHandler.postDelayed({
disconnectBl()
scanFailedCallBack()
}, 1 * 60 * 1000)
val filter = IntentFilter(BluetoothDevice.ACTION_FOUND)
context.registerReceiver(receiver, filter)
adapter?.startDiscovery()
}
private fun setReceiver() {
receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val action: String? = intent.action
when (action) {
BluetoothDevice.ACTION_FOUND -> {
val device: BluetoothDevice? =
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
val deviceName = device?.name
val deviceHardwareAddress = device?.address
Timber.d("name $deviceName")
if (deviceHardwareAddress == Const.blMac) {
Const.blDevice = device
disconnectBl()
showDialog()
return
}
}
}
}
}
}
fun disconnectBl() {
receiver?.let {
context.unregisterReceiver(receiver)
receiver = null
}
adapter?.cancelDiscovery()
}
private fun showDialog() {
PairingDialog().show(fm, null)
}
}
private lateinit var scanBluetooth: ConnectBluetooth.ConnectThread
scanBluetooth = ConnectBluetooth(
device = Const.blDevice!!,
context = requireContext(),
object : Handler(Looper.getMainLooper()) {
override fun handleMessage(msg: Message) {
super.handleMessage(msg)
val message = msg.obj.toString()
Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show()
}
},
object : Handler(Looper.getMainLooper()) {
override fun handleMessage(msg: Message) {
super.handleMessage(msg)
val message = msg.obj.toString()
Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show()
}
}
).ConnectThread()
scanBluetooth.start()
@SuppressLint("MissingPermission")
class ConnectBluetooth(
private val device: BluetoothDevice,
private val context: Context,
private val successHandler: Handler,
private val failHandler: Handler,
) {
val adapter = context.getBlAdapter()
private val blSocket: BluetoothSocket? by lazy(LazyThreadSafetyMode.NONE) {
device.createInsecureRfcommSocketToServiceRecord(uuid)
}
private var blSocket: BluetoothSocket? = null
inner class ConnectThread() : Thread() {
override fun run() {
super.run()
Const.blSocket = blSocket
adapter?.cancelDiscovery()
try {
blSocket?.let { socket ->
socket.connect()
}
} catch (e: Exception) {
e.printStackTrace()
val ms = failHandler.obtainMessage()
ms.obj = "블루투스에 연결 할 수 없습니다."
ms.sendToTarget()
return
}
val ms = successHandler.obtainMessage()
ms.obj = "블루투스에 연결되었습니다."
ms.sendToTarget()
}
}
}