我们能否通过设备的蓝牙或BLE信号唤醒Android应用-Android 8.0及更高版本

时间:2019-06-14 13:37:09

标签: android android-intent bluetooth ibeacon wakeup

我正在尝试通过附近的蓝牙设备唤醒我的Android应用。如果我强制关闭应用程序(在Android 8.0及更高版本中),并且在将我的Android设备靠近BLE设备时,是否可以获取回调或意图回调,以便可以推动ForeGround服务并使应用程序保持唤醒状态。

我尝试扫描附近的BLE设备,但是当应用被强行杀死时,BLE扫描停止,并且无法通过BLE附近的设备唤醒应用。

2 个答案:

答案 0 :(得分:1)

metinoy完全终止了应用程序。它不会获得FCM,Force stop中的警报也将被删除,等等。因此,应用程序进程将被完全杀死,所有信息也将被删除。

答案 1 :(得分:1)

是的。在Android 8+上,您可以使用与BroadcastReceiver关联的基于意图的扫描来基于BLE广告检测唤醒应用程序。只能将BroadcastReceiver运行几秒钟,但是您可以利用这段时间启动可以运行长达10分钟的即时JobService。 Android Beacon Library就是开箱即用的功能,可以进行背景检测。您也许还可以使用前台服务在后台运行超过10分钟。详细了解选项here

ScanSettings settings = (new ScanSettings.Builder().setScanMode(
                                ScanSettings.SCAN_MODE_LOW_POWER)).build();
// Make a scan filter matching the beacons I care about
List<ScanFilter> filters = getScanFilters(); 
BluetoothManager bluetoothManager =
            (BluetoothManager) mContext.getApplicationContext()
                                       .getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
Intent intent = new Intent(mContext, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent,
                                                         PendingIntent.FLAG_UPDATE_CURRENT);
bluetoothAdapter.getBluetoothLeScanner().startScan(filters, settings, pendingIntent);

上面的代码将设置一个触发的Intent,当检测到匹配的蓝牙设备时将触发对名为MyBroadcastReceiver的类的调用。然后,您可以像这样获取扫描数据:

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