【发布时间】:2017-01-23 21:11:52
【问题描述】:
我正在使用 Firebase 实时数据库开发一个聊天应用。我已经能够正确发送和接收消息。现在,我想在收到新消息时执行通知。为此,我创建了一个Service,它使用ChildEventListener 侦听数据库更改并创建通知。问题是我在onChildAdded 方法中创建通知,并且此方法会为数据库中的现有节点和新节点触发。这导致每当用户从应用程序来回导航时,都会为同一消息创建多次通知。
这是我的实现方式:
chatMsgsRef.orderByChild(FirebaseDBKeys.LOCATION_LAST_UPDATED).addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
ChatMessage message = dataSnapshot.getValue(ChatMessage.class);
if (!message.getSenderId().equals(currentUserId)) {
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(NotificationsService.this)
.setSmallIcon(R.drawable.message)
.setContentTitle("New Message from " + message.getReceipientName())
.setContentText(message.getMessage())
.setOnlyAlertOnce(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
mBuilder.setAutoCancel(true);
mBuilder.setLocalOnly(false);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
我如何实现通知在其他聊天应用程序(如 whatsapp 等)中的工作方式??
【问题讨论】:
-
你考虑过使用firebase-cloud-messaging吗?
-
Whatsapp 技术完全不同。它运行在客户端聊天存储codementor.io/vigneshwaranb/…
标签: android firebase notifications firebase-realtime-database