【问题标题】:i want to send firebase notification to user only when there is a change in database table我只想在数据库表发生更改时向用户发送 Firebase 通知
【发布时间】:2019-11-15 10:18:16
【问题描述】:

这是我的代码 问题是每次加载数据时都会触发它 我想要的是仅在数据库更改而不是在应用程序中加载数据时才应调用方法

   FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
    DatabaseReference reference = firebaseDatabase.getReference();

reference.child("Requests").addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
    DisplayNotification(getContext(),"New Order has been received");
  }

  @Override
  public void onCancelled(@NonNull DatabaseError databaseError) {

  }
});


 public void DisplayNotification(Context context, String message) {
    // Create an explicit intent for an Activity in your app
    Intent intent = new Intent(getContext(), MainActivity_User.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

    Uri NOTIFICATION_SOUND_URI = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + BuildConfig.APPLICATION_ID + "/" + R.raw.fillingyourinbox);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, "Default")
            .setSmallIcon(R.drawable.ic_launcher_background)
            .setContentTitle("New Order")
            .setContentText(message)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
            // Set the intent that will fire when the user taps the notification
            .setContentIntent(pendingIntent)
            .setAutoCancel(true);

    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

    // notificationId is a unique int for each notification that you must define
    notificationManager.notify(1, mBuilder.build());
}

【问题讨论】:

标签: android firebase firebase-realtime-database notifications


【解决方案1】:

你能忽略onDataChange的第一个电话吗?

private DataSnapshot lastObtainedDataSnapshot;
@Override
  public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
    if (lastObtainedDataSnapshot == null) {
    DisplayNotification(getContext(),"New Order has been received");
    }
    lastObtainedDataSnapshot = dataSnapshot;
  }

【讨论】:

  • 数据加载或打开应用时仍然收到通知
【解决方案2】:

您需要使用云功能来实现需求。

借助 Cloud Functions,您无需更新客户端代码即可处理 Firebase 实时数据库中的事件。 Cloud Functions 允许您以完全管理权限运行数据库操作,并确保对数据库的每次更改都单独处理。

onWrite(),在实时数据库中创建、更新或删除数据时触发。

onCreate(),在实时数据库中创建新数据时触发。

onUpdate(),当实时数据库中的数据更新时触发。

onDelete(),从实时数据库中删除数据时触发

在您的情况下,您需要使用 onCreate() 数据库触发器。您可以在此处阅读有关云功能的更多信息:

https://firebase.google.com/docs/functions/database-events

【讨论】:

  • 浏览了链接,但没有得到明确的答案,您有任何关于此的示例
  • @sagardeshmukh 如果答案对您有帮助,请将其标记为正确并点赞,以便其他人知道它有用,谢谢!
猜你喜欢
  • 2017-10-24
  • 1970-01-01
  • 2011-07-28
  • 2016-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多