我正在使用带有扫描过滤器的 blescan 来检测信标,它在前台和后台工作非常好,直到 oreo 版本,但是当涉及到 android pie 时,它无法在后台发送待处理的广播。
ScanSettings settings = (new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)).build();
final List<ScanFilter> scanFilters = new ArrayList<>();
scanFilters.add(getScanFilter());
BluetoothAdapter bluetoothAdapter;
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
Intent intent = new Intent(this.getApplicationContext(), MyBroadcastReceiver.class);
intent.putExtra("o-scan", true);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
bluetoothAdapter.getBluetoothLeScanner().startScan(scanFilters, settings, pendingIntent);
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int bleCallbackType = intent.getIntExtra(BluetoothLeScanner.EXTRA_CALLBACK_TYPE, -1);
if (bleCallbackType != -1) {
Log.d(TAG, "Passive background scan callback type: "+bleCallbackType);
ArrayList<ScanResult> scanResults = intent.getParcelableArrayListExtra(
BluetoothLeScanner.EXTRA_LIST_SCAN_RESULT);
// Do something with your ScanResult list here.
// These contain the data of your matching BLE advertising packets
}
}
}
最佳答案
Android 9 引入了多项行为变更,例如限制后台应用对设备传感器和 Wi-Fi 扫描的访问。
无论目标 SDK 版本如何,这些更改都会影响在 Android 9 上运行的所有应用。
使用连续报告模式的传感器,例如加速度计和陀螺仪,不接收事件。
Android 9 在后台对传感器的访问受限:
Android 9 限制了后台应用访问用户输入和传感器数据的能力。如果您的应用在运行 Android 9 的设备上后台运行,系统会对您的应用应用以下限制:
使用连续报告模式的传感器,例如加速度计和陀螺仪,不接收事件。
使用on-change 或one-shot 报告模式的传感器不接收事件。
解决方案: 如果您的应用需要在后台运行 Android 9 的设备上检测传感器事件,请使用前台服务。
关于java - BLE 扫描不能在后台使用 android pie 中的 Scanfilters 工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55757830/