android - 为什么我在打开活动时收到通知?
问题描述
编辑:有人在 STACKOVERFLOW 上有解决方案吗?
我正在使用 Firebase 数据库,并希望在添加新孩子后立即显示通知。
我正在使用“ChildEventListener”来获取它。
这是我的代码:
dbProducts.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
// Toast.makeText(ShowNotifActivity.this, "Child Added ", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(ShowNotifActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);
String channelId = "MyNotifications";
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), channelId)
.setSmallIcon(R.drawable.notification)
// .setLargeIcon(R.drawable.ic_notifications_active_black_24dp)
.setContentTitle("New Notification")
.setContentText("Click here to View ");
;
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId, "MyNotifications", NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
}
manager.notify(0, builder.build());
}
@Override
public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
// Toast.makeText(ShowNotifActivity.this, "Child Changed", Toast.LENGTH_SHORT).show();
}
@Override
public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
当在 firebase 数据库中添加新的孩子时,如何只显示一次通知。
问题是,只要我打开 Activity ,即使我没有更新通知也会触发它更改或在数据库中添加任何内容。如何修复
解决方案
当您使用addChildEventListener
在数据库中的某个位置附加侦听器时,onChildAdded
将为该位置的每个孩子调用一次,即使它不是新的。这就是为什么您的通知总是显示的原因。
如果您只想获得“新”项目,您将需要想出一种方法来确定哪些孩子对用户来说实际上是新的,并在您的查询中过滤这些孩子。也许时间戳或其他标志对您有用。
推荐阅读
- c# - 转换 web api 结果时获取不正确的日期
- java - 如何加密和解密大型视频文件
- python - 如何解决此错误值的长度与索引的长度不匹配
- java - 当使用非线程安全类是创建多个对象并将其传递给每个线程的可行设计时?
- javascript - 如何获取变量作为从控制器到 JavaScript 的响应?
- tesseract - “无法为 lang 加载任何 lstm 特定的字典” tesseract 4.1
- javascript - 按单词中元音的数量对句子进行排序并使用 javaScript 从左侧开始对其进行索引
- socket.io - 类实例不会在自身内部保存套接字
- linux - x86_64 :使用 40 位寻址而不是 48 位寻址
- java - 如何在公共目录中导入应用程序类