【问题标题】:Notification on New Child added to Fire-base Database , by using Service使用服务向 Fire-base Database 添加新孩子的通知
【发布时间】:2019-01-20 04:34:08
【问题描述】:

但是,即使没有将子项添加到数据库中,此代码也会在每天多次启动应用程序时显示通知 请帮我解决这个问题,我试过使用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());

        }

【问题讨论】:

    标签: android firebase-realtime-database android-service


    【解决方案1】:

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

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

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

    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(...
    

    有关更多信息,另请参阅:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-29
      • 1970-01-01
      • 2022-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-03
      • 2021-07-21
      相关资源
      最近更新 更多