@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
private fun discover(){
val mBluetoothLeScanner: BluetoothLeScanner =BluetoothAdapter.getDefaultAdapter().bluetoothLeScanner
val mHandler: Handler = Handler()
val scanCallback = object:ScanCallback() {
override fun onScanResult(callbackType: Int, result: ScanResult?) {
Log.d(TAG, "onscanresult...")
super.onScanResult(callbackType, result)
if (result == null || result.getDevice() == null || TextUtils.isEmpty(result.getDevice().getName())
) return
val builder = StringBuilder(result.getDevice().getName())
builder.append("\n").append(
result.getScanRecord()
?.getServiceData(result.getScanRecord()!!.getServiceUuids().get(0)),
Charset.forName("UTF-8")
)
//Observed result
Log.d(TAG, builder.toString())
}
override fun onBatchScanResults(results:List<ScanResult>?){
Log.d(TAG, "Scanning...")
super.onBatchScanResults(results)
}
override fun onScanFailed(errorCode: Int) {
Log.d(TAG, "Discovery onScanFailed: $errorCode")
super.onScanFailed(errorCode)
}
}
val filters: ArrayList<ScanFilter> = ArrayList<ScanFilter>()
val uuid = UUID.randomUUID()
val filter: ScanFilter = ScanFilter.Builder().setServiceUuid(ParcelUuid(UUID.fromString(uuid.toString()))).build()
filters.add(filter)
val settings: ScanSettings = ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build()
mBluetoothLeScanner?.startScan(filters, settings, scanCallback)
Log.d(TAG, "StartScan...")
mHandler.postDelayed(object : Runnable {
override fun run() {
mBluetoothLeScanner?.stopScan(scanCallback)
}
}, 10000)
finish()
}
On the code above, I have implemented BLE Scanning to receive a string. However, it seems like scanCallback has problem, but I am not sure what is it. On the Logcat, it shows "Startscan...", but it doesn't show "onscanresult...", so I assume the problem is on scanCallback. What could be the reason?? This code was written based on https://code.tutsplus.com/tutorials/how-to-advertise-android-as-a-bluetooth-le-peripheral--cms-25426, but as the example is in Java, I have implemented on Kotlin by myself. I have tried checking on the filters as well, but the problems seems to be on scanCallback.