【发布时间】:2018-11-25 14:05:18
【问题描述】:
我正在尝试将 Firebase FCM 集成到我的应用中,但我收到了消息 多次。
我通过一个云功能发送消息,每当通知添加到数据库时就会触发,如下所示:
import { DataSnapshot } from "firebase-functions/lib/providers/database";
import { EventContext } from "firebase-functions";
import * as admin from 'firebase-admin'
import { ResolvePromise } from "./misc";
export function doSendNoticeFCM(snapshot: DataSnapshot, context?: EventContext) {
const uid = context.params.uid;
const noticeid = String(context.params.noticeid);
const notice = snapshot.val();
return admin.database().ref('device-tokens').child(uid).child('0')
.on('value', (data) => {
const token = data.val();
if (token === null) {
return ResolvePromise();
}
const title = String(notice['Title']);
const body = String(notice['Body']);
console.log("Title: " + title);
console.log("Body: " + body);
const payload: admin.messaging.Message = {
data: {
notice_id: noticeid,
title: title,
body: body
},
android: {
ttl: 0
},
token: token
};
return admin.messaging().send(payload)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
});
}
这很好用,我检索设备令牌,发送消息,然后在我的消息服务的应用程序中接收它。
using System;
using Android.App;
using Android.Support.V4.App;
using Firebase.Messaging;
using Android.Util;
using Doshi.Xamarin.Abstractions.StaticData;
using Android.Content;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using Android;
using Xamarin.Forms;
using Plugin.CurrentActivity;
using Acr.UserDialogs;
using Doshi.Xamarin.Core.Helpers;
using Doshi.Xamarin.Abstractions.Misc;
using Doshi.Xamarin.Android.Logic.Interfaces;
using Doshi.Xamarin.Android.Logic.Implementations;
namespace Doshi.Droid
{
[Service(Name = "com.doshi.droid.DoshiMessagingService")]
[IntentFilter(new[] {"com.google.firebase.MESSAGING_EVENT"})]
public class DoshiMessagingService : FirebaseMessagingService
{
INoticePresenter _noticePresenter = new DoshiNoticePresenter();
public override void OnMessageReceived(RemoteMessage message)
{
HandleNotice(message);
}
private void HandleNotice(RemoteMessage message)
{
int id = DateTime.Now.Millisecond;
//Create the hardware notice.
_noticePresenter.PresentNotice(this, message, id, Xamarin.Droid.Resource.Drawable.ic_logo, typeof(MainActivity));
}
}
当我退出我的应用程序然后再次登录时会出现问题,我之前收到的相同通知再次收到。我在我的应用程序中使用带有 firebase 的 google 身份验证,并在我注销时从数据库中删除设备令牌,并在我再次登录时添加当前令牌。会不会是这个问题?
从我在 firebase 日志中看到的内容来看,云功能只对每条消息执行一次,所以我猜测客户端有问题。我在另一篇 stackoverflow 帖子中读到,将 ttl 设置为 0 可以解决此问题,但它不会影响我能看到的任何内容。
有没有其他人遇到过这个问题或知道我做错了什么? 我正在使用 Xamarin.Firebase.* nugets 的最新“稳定”版本。
【问题讨论】:
标签: c# android firebase xamarin firebase-cloud-messaging