0

但是即使没有将孩子添加到数据库中,此代码也会在每次应用启动时显示通知,并且每天多次显示请帮我解决这个问题,我已经尝试使用onDatabaseChange方法,但同样的事情正在发生

if (mChildEventListener == null) {
    mChildEventListener = new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            Intent intent = new Intent(getBaseContext(),MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(), 0, intent,
                    PendingIntent.FLAG_ONE_SHOT);

            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            NotificationCompat.Builder mnotificationBuilder = new NotificationCompat.Builder(getBaseContext())
                    .setSmallIcon(R.mipmap.ic_chat)
                    .setContentTitle("You may have New Messages !!")
                    .setContentText("Check Chat Room > Received > New Message")
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                    .setContentIntent(pendingIntent)
                    .setAutoCancel(true)
                    .setOnlyAlertOnce(true)
                    .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));



                notificationManager.notify(0, mnotificationBuilder.build());

        }
4

1 回答 1

0

当您将 a 附加ChildEventListener到某个位置时,onChildAdded会立即为该位置的所有现有子节点调用它。所以听起来代码按预期工作。

听起来您也只是想通知用户的子节点,可能意味着他们还没有看到的子节点。

一种简单的方法是跟踪您向用户显示的最新子节点。例如,通过将该节点的密钥存储在应用程序的共享首选项中。然后,当您加载应用程序时,您从共享首选项中读取密钥并从那里开始检索节点。

Query query = FirebaseDatabase.getInstance().getReference("messages").orderByKey();
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
String last_seen_message_key = prefs.getString("last_seen_message_key", null);
if (last_seen_message_key != null) {
  query = query.startAt(last_seen_message_key)
}
query.addChildEventListener(...

有关这方面的更多信息,另请参阅:

于 2019-01-20T04:54:25.167 回答