在前台服务中扫描BLE设备

时间:2018-05-30 20:27:52

标签: android bluetooth-lowenergy

我正在创建一个可以与类似于iBeacons的BLE设备检测和交换信息的应用。这些设备每1000毫秒发送一次广告。

目前,我有一个运行某些逻辑的前台服务,其中包括定期扫描BLE设备(例如每十秒一次,我运行扫描仪2秒)。然而,一旦我将应用程序推到后台,BLE扫描仪就会改变行为,不经常扫描。据我所知,这是因为操作系统强制扫描仪使用低功耗扫描模式。

问题在于扫描窗口比BLE设备广告间隔短,因此我倾向于错过数据包。有没有办法确保扫描能够运行至少这个间隔,可能是通过扫描模式(低延迟或平衡)或其他一些技巧?

我正在使用运行Android 7.0的三星Galaxy Tab S2。

编辑:添加了一些示例代码(注意:我使用的是Nativescript,因此您在此处看到的是将Nativescript代码转换为Java,据我所知。)

我用

启动服务
Intent intent = new Intent(this, com.my.service.MyService);
startService(intent);

服务类功能

@Override
public int onStartCommand(Intent intent, int flags, int startId){
    Notification notif = new Notification.Builder(this)
        .setContentInfo("My App")
        .build()

    this.startForeground(12312, notif);
    runMyScanner();
    this.super.onStartCommand(intent, flags, startId);
    return Service.START_STICKY;
}

public void onDestroy(){
    this.stopForeground(0); // Corresponds to a flag.
}

扫描仪

private int mNumScanned = 0;

public void runMyScanner(){
    List<ScanFilter> scanFilters = new ArrayList<>();
    scanFilters.add(new ScanFilter.Builder().build())

    ScanSettings scanSettings = new ScanSettings.Builder()
            .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
            .build()

    ScanCallback scanCallback = new ScanCallback(){

        @Override
        public void onScanResult(){
            mNumScanned++;
        }
    }

    mAdapter.getBluetoothLeScanner().startScan(scanFilterList, scanSettings, scanCallback);
}

(注意:扫描后,我打印出mNumScanned,这让我可以调查此问题。此外,我在启动后停止扫描几秒钟,但使用javascript方法setTimeout()这样做)

0 个答案:

没有答案
相关问题