【问题标题】:Not receiving notifications when app is killed FCM with Cloud Functions for Firebase使用 Cloud Functions for Firebase 杀死应用程序时未收到通知 FCM
【发布时间】:2017-08-10 08:18:32
【问题描述】:

Firebase 目前推出了带有 Firebase 的 Cloud Functions 以添加服务器端代码。

我目前正在使用这种方法来接收来自发件人的消息的通知。

一切似乎都很好,但是当我杀死应用程序时,我没有收到通知。

我看到了一些关于它的答案,我应该只使用数据消息并在onMessageReceived() 中接收,但它不适用于被杀死的应用程序。我该怎么办?

NodeJS Index.js

exports.sendNewMessageNotification = functions.database.ref('/rootssahaj/authGplus/users/{userTorS}/{userTeacherUID}/messages/{chatWithOthUser}/{messageUID}').onWrite(event => {
console.log('called1 ');
const TeacherUid = event.params.userTeacherUID;
const whoTorS=event.params.userTorS;
var whoOppTorS=null;
if (whoTorS=="teachers") {
    whoOppTorS="students";
}else{
    whoOppTorS="teachers";
}
var StudentUid = event.params.chatWithOthUser;
StudentUid=StudentUid.substring(8);

console.log('called2 ')

if (!event.data.val()) {
return console.log('No Change ');
}

console.log('Event data: ',StudentUid, event.data.val());
if (StudentUid!=event.data.val().sender) {
return console.log('Different sender ',event.data.val().sender);
}

// Get the list of device notification tokens.
const getDeviceTokensPromise = admin.database().ref(`/rootssahaj/authGplus/users/${whoTorS}/${TeacherUid}/profile/fcmtoken`).once('value');

// Get the follower profile.
const getFollowerProfilePromise = admin.database().ref(`/rootssahaj/authGplus/users/${whoOppTorS}/${StudentUid}/profile`).once('value');

return Promise.all([getDeviceTokensPromise, getFollowerProfilePromise]).then(results => {
const tokensSnapshot = results[0];
const follower = results[1];
console.log('Token: ', tokensSnapshot.val(),' ',follower.val());
// Check if there are any device tokens.
if (tokensSnapshot.val()==null) {
  return console.log('There are no notification tokens to send to.');
}
console.log('There are', tokensSnapshot.numChildren(), tokensSnapshot,'tokens to send notifications to.');
console.log('Fetched follower profile', follower.val().userNAME);

// Notification details.
const payload = {
  data: {
    body: `new message: ${event.data.val().text}`,
    title: `${follower.val().userNAME}`,
  }
};
var options = {
priority: "high"
};

// Listing all tokens.
//const tokens = Object.keys(tokensSnapshot.val());
// console.log('tokens', tokens);

// Send notifications to all tokens.
return admin.messaging().sendToDevice(tokensSnapshot.val(), payload,options).then(response => {
  // For each message check if there was an error.
  const tokensToRemove = [];
  response.results.forEach((result, index) => {
    const error = result.error;
    if (error) {
      console.error('Failure sending notification to', tokens[index], error);
      // Cleanup the tokens who are not registered anymore.
      if (error.code === 'messaging/invalid-registration-token' ||
          error.code === 'messaging/registration-token-not-registered') {
        //tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
      }
    }
  });
  return Promise.all(tokensToRemove);
});
});
});

这是我在应用终止状态下触发 Fcm 时收到的信息。我寻找它,但找不到合适的解决方案。

W/GCM-DMM (29459):广播意图回调:result=CANCELLED forIntent { act=com.google.android.c2dm.intent.RECEIVE flg=0x10000000 pkg=com.rana.sahaj.myyu(有附加功能) }

【问题讨论】:

    标签: android node.js firebase firebase-cloud-messaging google-cloud-functions


    【解决方案1】:

    请确保您在 Promise 中检索到的设备令牌是最新的。出于多种原因,设备令牌可以在模拟器或 Android 设备中更改/更新。

    请确认您在 Firebase 中的“函数”的“日志”选项卡下没有任何云函数的错误日志。

    我可以确认,当您终止应用(在 Android 中将应用刷掉)时,您仍然会收到通知。

    编辑:添加清单

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.google.firebase.quickstart.fcm">
        <uses-permission android:name="android.permission.READ_CALENDAR" />
        <uses-permission android:name="android.permission.WRITE_CALENDAR" />
        <application
            android:allowBackup="true"
            android:icon="@mipmap/app_logo"
            android:label="@string/app_name"
            android:theme="@style/AppTheme">
            <!-- [START fcm_default_icon] -->
    
            <meta-data
                android:name="com.google.firebase.messaging.default_notification_icon"
                android:resource="@drawable/ic_stat_ic_notification" />
    
            <meta-data
                android:name="com.google.firebase.messaging.default_notification_color"
                android:resource="@color/colorAccent" />
            <!-- [END fcm_default_icon] -->
            <activity
                android:name="com.google.firebase.quickstart.fcm.MainActivity"
                android:label="@string/app_name">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN"/>
                    <category android:name="android.intent.category.LAUNCHER"/>
                </intent-filter>
            </activity>
    
            <activity
                android:name="com.google.firebase.quickstart.fcm.CalendarActivity"
                android:label="@string/calendar_activity_label">
            </activity>
    
            <!-- [START firebase_service] -->
            <service
                android:name=".MyFirebaseMessagingService"
                android:enabled="true"
                android:exported="true">
                <intent-filter>
                    <action android:name="com.google.firebase.MESSAGING_EVENT"/>
                </intent-filter>
            </service>
            <!-- [END firebase_service] -->
            <!-- [START firebase_iid_service] -->
            <service
                android:name=".MyFirebaseInstanceIDService">
                <intent-filter>
                    <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
                </intent-filter>
            </service>
            <!-- [END firebase_iid_service] -->
        </application>
    
    </manifest>
    

    【讨论】:

    • 当应用程序没有被杀死时,我目前正在接收通知,并且我还编写了一个代码来更新该用户数据库中的令牌,以便可以直接从那里获取它。所以这不是问题,日志选项卡中也没有错误。你能告诉我你在 Manfiest 和 Receiver 中做了什么吗..
    • 以及你在哪个版本的android上测试过
    • 我在 firebase-database 和 firebase-messaging 都是 10.0.1。只是指出您正在发送数据类型消息,因此系统托盘中不会收到任何收到消息的通知。
    • 是的,但是应该触发 onMessageReceived()。 n 以前我使用的是 Notifications 类型,但结果是一样的,所以我寻找解决方案,在大多数解决方案中,它被编写为使其只是一种数据消息类型。
    • 我扩展了 FirebaseInstanceIdService 和 FirebaseMessagingService 并在服务中实现了所需的方法,在 AndroidManifest 中声明了服务。我希望您正在使用托管在 Github 上的消息传递快速入门应用程序。这是一个很好的起点
    【解决方案2】:

    Firebase 支持两种类型的通知:

    1. 通知消息
    2. 数据消息

    数据消息需要在客户端处理,应用被杀时收不到。

    Firebase 控制台会发送通知消息,因此即使应用被终止,您也会收到通知

    从云功能中,您需要在应用被杀死时发送通知消息以接收 enen

    //Notification message
    var patyload = {
        notification: {
           title: "title"
      }
    };
    
    //Data Message
    var payload = {
        data: {
          title: "title"
      }
    };
    
    admin.messaging().sendToTopic(topic, payload,options)
    

    在此处阅读有关通知的更多信息

    https://firebase.google.com/docs/cloud-messaging/concept-options

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多