The user is not allowed to swipe away a notification generated by an ongoing foreground service.
Hence, stopForeground(false)
first, which allows the notification to be swiped away by the user thereafter (at least on Lollipop+). For pre-Lollipop, you may have to stopForeground(true)
, which stops foreground and removes the notification, then re-issue the notification with notificationManager.notify(yourNotificationID, yourNotificationObject)
, so that your notification is visible but swipeable.
Crucially, set up the notification object with a delete intent that is triggered when the user swipes it away.
(new NotificationCompat.builder(this).setDeleteIntent(deletePendingIntent)).build()
where deletePendingIntent
is something like
Intent deleteIntent = new Intent(this, YourService.class);
deleteIntent.putExtra(someKey, someIntValue);
PendingIntent deletePendingIntent = PendingIntent.getService(this,
someIntValue,
deleteIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
When the user swipes it away, the intent with its extra is delivered to the service. Handle the delivered extra within onStartCommand
, i.e. check that intent != null
, intent.getExtras() != null
, then extract the value from the extras bundle given someKey
, and if it matches someIntValue
, then call stopSelf()
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…