I've created a 'LockscreenIntentReceiver' for my ongoing notification that looks like this:
private class LockscreenIntentReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
try {
String action = intent.getAction();
if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Log.d(TAG, "LockscreenIntentReceiver: ACTION_SCREEN_OFF");
disableNotification();
} else if (action.equals(Intent.ACTION_USER_PRESENT)){
Log.d(TAG, "LockscreenIntentReceiver: ACTION_USER_PRESENT");
// NOTE: Swipe unlocks don't have an official Intent/API in android for detection yet,
// and if we set ungoing control without a delay, it will get negated before it's created
// when pressing the lock/unlock button too fast consequently.
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (NotificationService.this.isNotificationAllowed()) {
enableNotification((Context)NotificationService.this);
}
}
}, 800);
}
} catch (Exception e) {
Log.e(TAG, "LockscreenIntentReceiver exception: " + e.toString());
}
}
}
This code will basically remove the ongoing notification when the user locks the phone (removal will be visible very briefly). And once the user unlocks the phone, the ongoing notification will be restored after the delay time (800 ms here). enableNotification() is a method which will create the notification, and call startForeground(). Currently verified to work on Android 7.1.1 .
You only have to remember to register & unregister the receiver accordingly.