Issue
I am trying to implement the most simple app to scan for a BLE device. I have given the necessary rights:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
However, onScanResult never gets called. Bluetooth is enabled on my phone and the BLE device is on, this is my code:
class MainActivity : AppCompatActivity() {
private val bleScanner = object :ScanCallback() {
override fun onScanResult(callbackType: Int, result: ScanResult) {
Log.d("DeviceListActivity", "onScanResult()")
super.onScanResult(callbackType, result)
val device = result.device
Log.d("DeviceScanner", "Device found: ${device.address} - ${device.name ?: "Unknown"}")
//Log.d("DeviceListActivity","onScanResult: ${result.device?.address} - ${result.device?.name}")
}
}
private val bluetoothLeScanner: BluetoothLeScanner
get() {
val bluetoothManager = applicationContext.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
val bluetoothAdapter: BluetoothAdapter = bluetoothManager.adapter
return bluetoothAdapter.bluetoothLeScanner
}
override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
Log.d("DeviceListActivity", "onCreate()")
super.onCreate(savedInstanceState, persistentState)
setContentView(R.layout.activity_device_list)
}
override fun onStart() {
Log.d("DeviceListActivity", "onStart()")
super.onStart()
enableLocation()
bluetoothLeScanner.startScan(bleScanner)
}
override fun onStop() {
Log.d("DeviceListActivity", "onStop()")
bluetoothLeScanner.stopScan(bleScanner)
super.onStop()
}
private fun enableLocation(): Boolean {
val service = applicationContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
val enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER)
return enabled
}
}
What am I missing?
Solution
Yes it was the missing requested permission. I inserted following function into onResume()
if (ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
0
)
} else {
leDeviceScanner.start()
}
It now workes like a charm. Thanks!
Answered By - HBJesus
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.