繁体   English   中英

取消通知 Android Java

[英]Canceling Notififcations Android Java

我开始使用通知并改善用户体验,我在通知“标记为已读”中添加了按钮,因此当它被按下时 - 消息将隐藏;

我遇到了一些问题,在数据库中,每条消息都有“读取”字段,它是布尔值,在方法 onDataChange() 中,我循环并检查是否有任何消息将此字段设为 false,如果它们有我调用 makeNotification(),看起来不错,在哪里有问题??? - 例如,我有 2 个通知,我取消了一个(应用程序转到数据库并将字段更改为 true,所以现在将调用 onDataChange()),但另一个没有取消,因为现在调用了 onDataChange() 我有相同的通知出现了两次.....

我试图通过构建已读取并已显示的消息数组来解决此问题,这不是我认为的最佳解决方案,但即使以前的问题也以某种方式解决了,这是一个奇怪的问题。 当通知出现在通知列表中时,它有按钮“标记为已读”,当我按下它时,通知会隐藏,但前提是我从高到低开始,所以如果我先按第二个通知折叠,如果我按第三个第一个折叠..

在 onCreate() 计数器设置为 1;

public void makeNotification()
{
    Intent activityIntent  = new Intent(this, Notifications.class);
    PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, activityIntent, 0);

    Intent broadcastIntent = new Intent(getApplicationContext(), NotifUpdater.class);
    broadcastIntent.putExtra("seconds", message.getSeconds());
    broadcastIntent.putExtra("id", String.valueOf(counter));

    PendingIntent actionIntent = PendingIntent.getBroadcast(this, 0,
            broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    Notification notification = new NotificationCompat.Builder(this, App.CHANNEL_ID)
            .setVibrate(new long[]{100, 0, 100})
            .setSmallIcon(R.drawable.ic_shield)
            .setContentTitle(message.getTime() + " | " + message.getClient())
            .setContentText(message.getMessage())
            .setContentIntent(contentIntent)
            .setAutoCancel(true)
            .setOnlyAlertOnce(true)
            .addAction(0, "MARK AS READ", actionIntent)
            .build();

    notificationManager.notify(counter, notification);
    counter += 1;
}

// Broadcast which is triggered by pressing button
public class NotifUpdater extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    String seconds = intent.getStringExtra("seconds");
    int id = Integer.parseInt(intent.getStringExtra("id"));
    database.getReference("latest").child(seconds).child("read").setValue(true);

    NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
    notificationManager.cancel(id);
    }
}

关于你的第一个问题,我只是为每个通知设置一个指示器,“wasShown”或类似的东西,只有在你显示通知后才设置为 true,并且当你迭代通知时,只显示那些已经“wasShown”设置为false。

关于您的第二个问题,我不熟悉 FirebaseDatabase,但听起来像是 ID 问题。 您是否确保从意图中获得的 ID 是正确的?

你应该有: FLAG_CANCEL_CURRENT像:

PendingIntent actionIntent = PendingIntent.getBroadcast(this, NOTIFICATION_ID, buttonIntent, PendingIntent.FLAG_CANCEL_CURRENT);

不是FLAG_UPDATE_CURRENT

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM