首页 文章

每当触摸Android中的任何通知时,为什么通知始终显示最后通知

提问于
浏览
0

我试图在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 Class中编写的代码 .

@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会在创建新意图时覆盖所有意图数据 .

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

如果有任何其他方法不通过notificationId和消息保留每个通知?

1 回答

  • 0

    我找到了为每个intent添加randon requestCode而不是为每个intent使用0的解决方案 .

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

相关问题