我的应用中有通知,此通知包含使用addAction()方法设置的按钮。但每次用户点击通知按钮时,通知都不会自动取消,除非该用户在通知中明确点击。
private static void notification(Context context, String title, String text, int id, Intent intent, int priority, boolean withSound) {
PendingIntent pendingIntent = PendingIntent.getActivity(context, Constants.REQUEST_CODE_NOTIFICATION, intent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context);
notificationBuilder.setSmallIcon(R.drawable.ic_stat_notify);
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(text);
notificationBuilder.setColor(ContextCompat.getColor(context, R.color.bg_primary));
notificationBuilder.setAutoCancel(true);
notificationBuilder.setContentIntent(pendingIntent);
notificationBuilder.setPriority(priority);
if (Constants.NOTIFICATION_NEW_AD_BALANCE == id)
notificationBuilder.setTicker(text);
if (Constants.NOTIFICATION_DATE_TIME_SETTINGS == id)
notificationBuilder.addAction(0, context.getString(R.string.notification_device_time_settings), pendingIntent).setAutoCancel(true);
notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(text));
if (withSound) {
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationBuilder.setSound(alarmSound);
notificationBuilder.setVibrate(new long[]{500, 500});
} else {
notificationBuilder.setVibrate(new long[0]);
}
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(id, notificationBuilder.build());
}
答案 0 :(得分:1)
要解决此问题,我必须使用以下待处理意图开始我的通知:
pendingIntent = PendingIntent.getBroadcast(context, Constants.REQUEST_CODE_NOTIFICATION, intent, PendingIntent.FLAG_CANCEL_CURRENT);
在用户执行点击通知按钮后我必须实现广播接收器时,你怎么能看到以下内容:
public class DateTimeSettingsBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
context.startActivity(new Intent(Settings.ACTION_DATE_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
NotificationBuilder.cancel(context, Constants.NOTIFICATION_DATE_TIME_SETTINGS);
}
}
这样就解决了用户执行点击后没有解除通知的问题。
答案 1 :(得分:0)
您对setAutoCancel()
的期望是什么?阅读docs,它说
设置此标志将使用户在用户单击面板时自动取消通知。
听起来你的代码工作正常。我相信你想要在添加新通知时解除之前的通知吗?我不记得肯定,但我认为如果你使用相同的id
,它将取代现有的id
。否则,我知道您可以使用notificationManager.cancel(id);
:
List<? super X>