2

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

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

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

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

NodeJS 索引.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 (有额外) }

4

2 回答 2

0

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

于 2017-12-11T15:08:10.657 回答
0

请确保您在 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>
于 2017-03-19T05:59:29.987 回答