@Sabid Habib 的答案是正确的,但它应该使用自定义本地广播,而不是使用系统级广播,如下面定义的以及一些优化
定义您的自定义广播接收器,并放置一个静态布尔值NotificationService.sEnabled
以检查您所需的服务是否已经在运行,如果您不想不必要地启动服务,还可以进行其他检查,您还可以向服务发送布尔值notificationServiceIntent.putExtra(NotificationService.EXTRA_RUN_IN_FOREGROUND, true);
以指示该服务只应重新启动前台通知而不是完全重新启动它onStartCommand
public class NotificationRemovalReceiver extends BroadcastReceiver {
public static final String FILTER_NOTIFICATION_REMOVED = "FILTER_NOTIFICATION_REMOVED";
@Override
public void onReceive(Context context, Intent intent) {
if(NotificationService.sEnabled) {
Intent notificationServiceIntent = new Intent(context, NotificationService.class);
notificationServiceIntent.putExtra(NotificationService.EXTRA_RUN_IN_FOREGROUND, true);
context.startService(notificationServiceIntent);
}
}
}
添加此广播接收器以获取删除通知
Intent removeNotificationIntent = new Intent(NotificationRemovalReceiver.FILTER_NOTIFICATION_REMOVED);
PendingIntent removeNotificationPendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, removeNotificationIntent, 0);
Notification mNotification = new NotificationCompat.Builder(this, getNotificationChannelId())
.setContentTitle(title)
.setContentText(text)
.setSmallIcon(smallIcon)
.setDeleteIntent(removeNotificationPendingIntent)
.setContentIntent(pendingIntent).build();
startForeground(NOTIFICATION_ID, mNotification);
在清单文件中定义您的接收器
<receiver android:name=".receivers.NotificationRemovalReceiver" >
<intent-filter>
<action android:name="FILTER_NOTIFICATION_REMOVED" >
</action>
</intent-filter>
</receiver>