IoT 项目,当实时数据库中的值更新时,如何获取 android 通知?

IoT project, How to get a andorid notification when a value is UPDATED in the realtime databe?

我正在做一个物联网项目,我将数据从 7 个不同的 NodeMCU 传感器节点发送到 FIREBASE 实时数据库。我正在使用 Android 应用程序作为 HMI,用户可以使用应用程序在数据库中读取和写入。

我想做的是,当其中一个节点更新数据库中的值时,用户会收到通知,无论用户是在应用程序中还是在应用程序之外。我读过很多教程,其中用户使用应用程序在数据库中写入,然后接收他所写内容的通知,这里节点更新值,应用程序通知用户值已更新。

我试过的东西。

云函数,我已经设置了一个 onUpdate typescript 函数,但我没有在控制台日志中显示更改。

我将向您展示我的 firebase 结构。

如您所见,节点更新的值是真或假,我需要当 ACT/IN1 更新为真时,用户会收到通知。

希望我说得足够清楚,以便您能帮助我。

您可以使用 OnTrigger 事件从 Cloud Functions 触发此操作。

exports.makeUppercase = functions.database.ref('/datos/ACT/{item}')
    .onUpdate((change, context) => {
      const newValue = change.after.val();
      const oldValue = change.before.val();
      // Send FCM here
    });

从那里,您可以使用逻辑来确定是否要发送通知。

const message = {
  data: {
    score: '850',
    time: '2:45'
  },
  token: registrationToken
};

// Send a message to the device corresponding to the provided
// registration token.
admin.messaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

您只需从设备中查找或存储注册令牌即可知道将通知发送到哪里,可以根据文档找到通知