I’ve been struggling with this issue for a long time and have searched through many articles, but still haven’t found a solution. Could you please provide me with some direction?
I’m using intent-based Bluetooth scanning to continuously operate in the background, and the experimental results have been very good (I can correctly receive the Bluetooth list in the onReceive
method of the BroadcastReceiver, and it can run for a long time).
However! When I try to stop the scan using stopScan
, at first I thought it stopped normally, but after a while, without opening the application, I receive scan results again.
What exactly happened? Why is it that even though stopScan
was called, results are still being received?
I have used both the native SDK and the Android-Scanner-Compat-Library for the Bluetooth part. Below is the Android-Scanner-Compat-Library.
I’m not sure if the provided information is sufficient to identify the issue.
If there’s any additional content you need from me, please let me know.
<receiver
android:name=".BluetoothReceiver"
android:exported="false">
<intent-filter>
<action android:name="BluetoothDevice.ACTION_FOUND" />
</intent-filter>
</receiver>
private fun startBluetoothLeScanIntent() {
val filters = ArrayList<ScanFilter>()
val filter = ScanFilter.Builder()
.setServiceUuid(ParcelUuid(UUID.fromString(UUID_STRING)))
.build()
filters.add(filter)
val settings = ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)
.build()
val intent = Intent(requireContext(), BluetoothReceiver::class.java)
intent.putExtra("test", "")
pendingIntent = PendingIntent.getBroadcast(requireContext(), 0, intent, FLAG_UPDATE_CURRENT or FLAG_MUTABLE)
BluetoothLeScannerCompat.getScanner().startScan(
filters,
settings,
requireContext(),
pendingIntent,
0
)
}
private fun stopBluetoothLeScanIntent() {
BluetoothLeScannerCompat.getScanner().stopScan(requireContext(), pendingIntent, 0)
}
class BluetoothReceiver : BroadcastReceiver() {
companion object {
private val TAG = BluetoothReceiver::class.simpleName
}
override fun onReceive(context: Context, intent: Intent) {
val hasBleExtra = intent.hasExtra(BluetoothLeScannerCompat.EXTRA_CALLBACK_TYPE)
if (hasBleExtra) {
val bleCallbackType =
intent.getIntExtra(BluetoothLeScannerCompat.EXTRA_CALLBACK_TYPE, -1)
if (bleCallbackType != -1) {
// ...
}
}
}
}
yjw is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.