问题
I'm currently getting a headache with sticky notifications while trying to stop and restart foreground scanning in altbeacon.
What I want to do: I want to start scanning for Bluetooth LE Beacons in a vehicle after the User presses a Button in my App. The App should notice if the User leaves his vehicle (event region left) and perform some actions. After that, the User can go back to the login screen and start the process again. The Beacon detection should still be working when the app is minimized.
My current solution:
I implemented Altbeacon in my Application class. In the Applications onCreate, I initialize the BeaconManager (getInstance, set BeaconParsers, etc.).
When the user clicks the button, I call startMonitoring
to start a foreground scan:
public void startMonitoring() {
Notification.Builder builder = new Notification.Builder(this);
builder.setSmallIcon(R.drawable.notificationicon);
builder.setContentTitle("Content Title");
builder.setContentText("Content Text");
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT
);
builder.setContentIntent(pendingIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("ChannelId", "ChannelName", NotificationManager.IMPORTANCE_LOW);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Objects.requireNonNull(notificationManager).createNotificationChannel(channel);
builder.setChannelId(channel.getId());
}
beaconManager.enableForegroundServiceScanning(builder.build(), 12345);
beaconManager.setEnableScheduledScanJobs(false);
beaconManager.setBackgroundBetweenScanPeriod(0);
beaconManager.setBackgroundScanPeriod(1100);
beaconManager.bind(this);
}
When I detect that the User left the vehicle, I call stopMonitoring
to stop the foreground scan and remove the notification:
public void stopMonitoring() {
beaconManager.unbind(this);
beaconManager.disableForegroundServiceScanning();
}
Disabling the foreground scan should normally remove the sticky notification or at least make it removable (by swiping) to the user. This isn't the case. I was able to remove the notification by deleting the notification channel:
public void stopMonitoring() {
[...]
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.deleteNotificationChannel("ChannelId");
}
}
But when I do this, the app won't show the notification again.
Does anyone have an idea on how to stop and restart foreground scanning properly?
来源:https://stackoverflow.com/questions/55867353/stopping-and-restarting-foreground-service-scanning-with-altbeacon