BLE扫描无法在Android环境中使用Scanfilters在后台运行?

问题描述 投票:0回答:2

我正在使用带有扫描过滤器的blescan来检测信标,它在前景和后台工作得非常好,直到奥利奥版本,但是当涉及到android馅饼时,它无法在后台发送待处理的广播。

  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
        }
    }
}


java android bluetooth-lowenergy android-9.0-pie
2个回答
1
投票

Android 9引入了一些行为更改,例如限制后台应用程序访问设备传感器和Wi-Fi扫描。

无论目标SDK版本如何,这些更改都会影响在Android 9上运行的所有应用。

使用连续报告模式的传感器(如加速度计和陀螺仪)不会接收事件。


Android 9限制访问后台传感器:

Android 9限制了后台应用访问用户输入和传感器数据的能力。如果您的应用在运行Android 9的设备上在后台运行,系统会对您的应用应用以下限制:

使用连续报告模式的传感器(如加速度计和陀螺仪)不会接收事件。

使用变更或一次性报告模式的传感器不会接收事件。


解决方案:如果您的应用需要在应用程序位于后台时检测运行Android 9的设备上的传感器事件,请使用前台服务。


0
投票

我是一个使用Oreo(API 26)测试Android应用程序的示例,以及上面的代码(稍加修改)来检测信标。我正在使用Pixel 3 XL(带Pie)。我认为关于这一点的困难部分是确定当设备仅在电池上运行时,MyBroadcastReceiver中的onRecieve()中的代码是否实际上在检测到信标时运行(与Android-studio和Logcat(USB)断开连接) )。

使用Volley(com.android.volley)向本地http服务器提交HTTP请求,我能够证明它的工作原理 - 即。我能够在检测到信标时收到http请求。但是,当Android处于唤醒状态或周期性地唤醒并连接到网络时,Volley只发送这些请求 - 这在我的简单测试中大约每15分钟(加上一些变化),但我确实得到了所有的信标ScanResults HTTP服务器,最多延迟15分钟。我甚至能够从正在运行的应用程序列表中删除该应用程序(您知道;向上滑动以删除应用程序)并仍然看到MyBroadcastReceiver中的onRecieve()正在接收BLE ScanResults。

你怎么知道广播接收器中的onReceive()被杀了?我很想知道你是怎么知道的。

© www.soinside.com 2019 - 2024. All rights reserved.