2

Firebase currently rolled out Cloud Functions with Firebase to add server side code.

I am currently using this approach for notifications on receiving a message from a sender.

Everything seems fine but when i kill the app I dont receive notifications.

I saw some answers regarding it that i should use just data message and receive in onMessageReceived() but its not working for killed app. What should i do?

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);
});
});
});

This is what i receive when Fcm is fired on app killed state. I looked for it but couldn't find a proper solution to solve it.

W/GCM-DMM (29459): broadcast intent callback: result=CANCELLED forIntent { act=com.google.android.c2dm.intent.RECEIVE flg=0x10000000 pkg= com.rana.sahaj.myyu (has extras) }

Sahaj Rana
  • 1,993
  • 4
  • 25
  • 42

2 Answers2

0

Please make sure the device token you retrieve in your promise is up to date. The device token can change/update in the emulator or Android device for a number of reasons.

Please confirm you don't have any error logs for the cloud function under the LOGS tab in Functions in Firebase.

I can CONFIRM when you kill the app (swipe the app away in Android) you still receive notifications.

EDIT : Added Manifest

<?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>
Yazan
  • 6,074
  • 1
  • 19
  • 33
user3414265
  • 23
  • 1
  • 6
  • I am currently receiving notifications when app is not killed and I have also made a code to update the token in database of that user so that it could be directly fetched from there. so thats not the issue and also no errors in logs tab. Could u tell me what have you done in your Manfiest and Receiver.. – Sahaj Rana Mar 19 '17 at 06:12
  • and which version of android you have tested on – Sahaj Rana Mar 19 '17 at 06:12
  • I am on firebase-database & firebase-messaging both 10.0.1. Just pointing out you are sending a data type message so, there will be no notification in the System tray of any message received. – user3414265 Mar 19 '17 at 06:22
  • Yaa, but onMessageReceived() should be fired. n previously I was using Notifications type but the result was same so i looked for solution and in most of them it was written to make it just a data message type. – Sahaj Rana Mar 19 '17 at 06:25
  • I have extended FirebaseInstanceIdService and FirebaseMessagingService and implemented the required methods in the service, declared the services in AndroidManifest. I hope you are using the messaging quickstart app hosted on Github. It is a good starting point – user3414265 Mar 19 '17 at 06:28
  • Jut to confirm what do you mean by app killed - You swipe the app from the recent app list OR force stop the app? If you Force stop the app, you will not receive notifications unless you launch the app again. – user3414265 Mar 19 '17 at 06:36
  • and its more like removing app from system tray – Sahaj Rana Mar 19 '17 at 06:51
  • Please note it may work in previous versions of Android but is not working from Lollipop on wards, just tested on my Android device. – user3414265 Mar 19 '17 at 07:09
0

Firebase support two types of notification:

  1. Notification message
  2. Data message

Data message need to be processed on client side and does not receive when app is killed.

Firebase console sends notification message so you receive them even when the app is killed

From cloud function you need to send a notification message to receive enen when app is killed

//Notification message
var patyload = {
    notification: {
       title: "title"
  }
};

//Data Message
var payload = {
    data: {
      title: "title"
  }
};

admin.messaging().sendToTopic(topic, payload,options)

Read more about notification here

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

Shruti
  • 5
  • 1
  • 1