gpt4 book ai didi

android - 为什么只要触摸android中的任何通知,通知总是显示最后一个通知

转载 作者:行者123 更新时间:2023-11-29 19:46:12 24 4
gpt4 key购买 nike

我尝试在 Android 应用程序中创建通知。创建一笔交易后,我调用“ShowNotification”方法在设备中显示通知。

public void showNotification(String screen, String message) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("screen", screen);
intent.putExtra("message",message);
int id = 1;
try {
// get latest id from SQLite DB
id = DbManager.getInstance().getIntDbKeyValue("notif_id");
if (id < 1) {
id = 1;
}
} catch (Exception e) {
}
intent.putExtra("notif_id", id + "");

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification n = new Notification.Builder(this).setContentTitle(getString(R.string.app_name)).setContentText(message)
.setSmallIcon(R.drawable.ic_launcher).setContentIntent(pIntent).setAutoCancel(true)
.setStyle(new Notification.BigTextStyle().bigText(message))
.build();
// set next running id into SQLite DB
DbManager.getInstance().setDbKeyValue("notif_id", (id + 1) + "");
notificationManager.notify(id, n);
}

我可以在设备的通知列表中看到正确的消息。当我触摸通知时,我想在屏幕上显示带有警报的消息。

问题是每当我触摸通知时,它总是在警告框中显示最后一个通知。下面是我在 MainActivity 类中编写的代码。

@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
try {
checkIntent(intent);
} catch (Exception e) {
e.printStackTrace();
}
}

private void checkIntent(Intent intent) {
try {
int id = Integer.parseInt(intent.getStringExtra("notif_id"));
if (id > 0 ) {
String s = intent.getStringExtra("screen");
if ("XXXXXX".equalsIgnoreCase(s)) {
Fragment f = new MonitoringFragment();
Bundle bundle = new Bundle();
bundle.putString("message", intent.getStringExtra("message"));
f.setArguments(bundle);
showFragment(f, false);
}else{
showFragment(new XxxxFragment(), false);
}
}
} catch (Exception e) {
}
}

你们中的任何人都可以告诉我为什么每当我触摸通知时它总是得到最后的 NOtificationID 吗?

我怀疑 PendingIntent 会在创建新 Intent 时覆盖所有 Intent 数据。

PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

是否有任何其他方法可以不保留每个通知及其 notificationId 和消息?

最佳答案

我找到了为每个 Intent 添加随机请求代码而不是为每个 Intent 使用 0 的解决方案。

int requestCode = new Random().nextInt();
PendingIntent pIntent = PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);

关于android - 为什么只要触摸android中的任何通知,通知总是显示最后一个通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37607528/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com