fix for IllegalStateException also when stopping the OngoingNotificationsService

This commit is contained in:
Philipp Crocoll
2018-06-06 02:57:50 +02:00
parent 3ca462f46f
commit 3c19f8e76f
2 changed files with 28 additions and 15 deletions

View File

@@ -240,14 +240,21 @@ namespace keepass2android
{
// Start or update the notification icon service to reflect the current state
var ctx = Application.Context;
StartOnGoingService(ctx);
}
if (DatabaseIsUnlocked || QuickLocked)
{
ContextCompat.StartForegroundService(ctx, new Intent(ctx, typeof(OngoingNotificationsService)));
}
else
{
//Anrdoid 8 requires that we call StartForeground() shortly after starting the service with StartForegroundService.
//This is not possible when we're closing the service. In this case we don't use the StopSelf in the OngoingNotificationsService.OnStartCommand() anymore but directly stop the service.
public static void StartOnGoingService(Context ctx)
{
ContextCompat.StartForegroundService(ctx, new Intent(ctx, typeof (OngoingNotificationsService)));
}
OngoingNotificationsService.CancelNotifications(ctx); //The docs are not 100% clear if OnDestroy() will be called immediately. So make sure the notifications are up to date.
ctx.StopService(new Intent(ctx, typeof(OngoingNotificationsService)));
}
}
public bool DatabaseIsUnlocked
{
get { return _db.Loaded && !QuickLocked; }

View File

@@ -48,7 +48,7 @@ namespace keepass2android
public override void OnCreate()
{
base.OnCreate();
_screenOffReceiver = new ScreenOffReceiver();
IntentFilter filter = new IntentFilter();
filter.AddAction(Intent.ActionScreenOff);
@@ -104,24 +104,30 @@ namespace keepass2android
{
base.OnDestroy();
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.Cancel(UnlockedWarningId);
// Quick Unlock notification should be removed automatically by the service (if present), as it was the foreground notification.
CancelNotifications(this);
Kp2aLog.Log("OngoingNotificationsService.OnDestroy");
Kp2aLog.Log("OngoingNotificationsService.OnDestroy");
// If the service is killed, then lock the database immediately
if (App.Kp2a.DatabaseIsUnlocked)
{
App.Kp2a.LockDatabase();
}
//also remove any notifications of the app
notificationManager.CancelAll();
UnregisterReceiver(_screenOffReceiver);
}
public override IBinder OnBind(Intent intent)
public static void CancelNotifications(Context ctx)
{
var notificationManager = (NotificationManager) ctx.GetSystemService(NotificationService);
notificationManager.Cancel(UnlockedWarningId);
// Quick Unlock notification should be removed automatically by the service (if present), as it was the foreground notification.
//also remove any notifications of the app
notificationManager.CancelAll();
}
public override IBinder OnBind(Intent intent)
{
return null;
}