我有一个本地通知,在我的一个接收器中设置。通知我想要打开一个特定的活动。以下是我的代码。
NotificationCompat.Builder builder =
(NotificationCompat.Builder) new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Its Your day!!")
.setContentText(message)
.setAutoCancel(true);
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
// Add as notification
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(times, builder.build());
但这不起作用。单击通知时,它只会从状态栏中删除通知。我错过了什么吗?
答案 0 :(得分:1)
试试这个:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
而不是:
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
在通知构建器代码之前使用此代码。
现在这是完整版:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder builder =
(NotificationCompat.Builder) new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Its Your day!!")
.setContentText(message)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(times, notificationBuilder.build());
尝试使用它。我希望你能得到你想要的答案。
<强>更新强>
这是示例项目:https://github.com/ImtiazDipto01/SimpleNotification
答案 1 :(得分:0)
在{Intent}上添加Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP
作为Flag
。喜欢 -
notificationIntent .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
还提供通知的唯一ID。喜欢 -
int uniqueNotificationId = (int) (System.currentTimeMillis() & 0xfffffff);
PendingIntent contentIntent = PendingIntent.getActivity(context, uniqueNotificationId , notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
同样在 -
manager.notify(uniqueNotificationId , builder.build());