Shawn Karber_
05/04/2020, 10:47 PMMatt Lien
05/05/2020, 1:14 AMprivate val bluetoothAdapter: BluetoothAdapter? by lazy(LazyThreadSafetyMode.NONE) {
val bluetoothManager = activity?.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
bluetoothManager.adapter
}
private val bleScanCallback = object: ScanCallback() {
override fun onScanFailed(errorCode: Int) {
super.onScanFailed(errorCode)
}
override fun onScanResult(callbackType: Int, result: ScanResult?) {
super.onScanResult(callbackType, result)
result?.let {
viewModel.addBleDevice(it.device)
}
}
override fun onBatchScanResults(results: MutableList<ScanResult>?) {
super.onBatchScanResults(results)
results?.forEach { result ->
viewModel.addBleDevice(result.device)
}
}
}
private fun scanForBleDevices() {
when(ContextCompat.checkSelfPermission(activity!!, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
true -> {
Handler().postDelayed({
bluetoothAdapter?.bluetoothLeScanner?.stopScan(bleScanCallback)
viewModel.onBleScanFinished()
}, 5000)
bluetoothAdapter?.bluetoothLeScanner?.startScan(bleScanCallback)
}
else -> {
requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), RequestCode.REQUEST_ACCESS_FINE_LOCATION_PERMISSION)
}
}
}
rahul_lohra
05/06/2020, 10:03 AM