Home » Android » android – Not receiving notifications from FCM-Exceptionshub

android – Not receiving notifications from FCM-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment

Questions:

I have a function (Firebase Functions) that sends a notification to a specific device if he receives a message.
The function works as expected but the receiver never gets the notification even tho, in the Firebase Console Log this outputs:

Successfully sent message:  { results: [ { messageId: '0:1581972223155663%ca6aa243f9fd7ecd' } ],
  canonicalRegistrationTokenCount: 0,
  failureCount: 0,
  successCount: 1,
  multicastId: 7431837786357220000 }

This is the functions code:

  const functions = require('firebase-functions');

  const admin = require('firebase-admin');

  admin.initializeApp(functions.config().firebase);

// When a new message is added, we retrieve it's content
  exports.sendNotification = functions.database.ref("/chats/{id}/messages/{messageId}")
  .onCreate((change,context) => {
      var content = change.val();
      console.log("Content is = ", content);


      // This is the user ID who is supposed to receive the sendNotification
      // Note that this ISN'T the token....
      var userWhoReceivedTheMessageId = content.receiver;
      console.log("Receiver ID = ", userWhoReceivedTheMessageId);

      // This is the payload. Title is a constant and the text is the message received.
      var payload = {
          data:{
              title: "Stranger has sent you a message",
              text: content.content
          }
      };



      // Gets the token
      const refSenderId = admin.database().ref("/users/" + userWhoReceivedTheMessageId + "/token");
      return refSenderId.once('value')
        .then(dataSnapshot => {
              const token = dataSnapshot.val();
              console.log("Token is: ", token);
              return admin.messaging().sendToDevice(token, payload);
        })
        .then(function(response){
            console.log("Successfully sent message: ", response);
            return null;
        })
        .catch(function(error){
            console.log("Error sending message: ", error);
            return null;
        })
  });

And, in android studio, this is where I have my service ready to check for notifications:

class MyFirebaseInstanceId : FirebaseMessagingService() {
    override fun onMessageReceived(p0: RemoteMessage) {
        if(p0.data.size > 0){
            val payload :Map<String, String> = p0.data

            sendNotification(payload)

        }
    }

    override fun onNewToken(p0: String) {
        super.onNewToken(p0)

        // save the token
        FirebaseDatabase.getInstance().reference.child("users").child(MainActivity.auth.currentUser?.uid.toString()).child("token").setValue(p0)
        Log.i("TOKEN", p0)
    }

    private fun sendNotification(payload: Map<String, String>) {
        val builder = NotificationCompat.Builder(this)
        builder.setSmallIcon(R.drawable.common_google_signin_btn_icon_disabled)
        builder.setContentTitle(payload.get("title"))
        builder.setContentText(payload.get("text"))

        val intent = Intent(this, MainActivity::class.java)
        val stackBuilder = TaskStackBuilder.create(this)

        stackBuilder.addNextIntent(intent)

        val resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)

        builder.setContentIntent(resultPendingIntent)

        val notificationManager =  (getSystemService(Context.NOTIFICATION_SERVICE)) as NotificationManager

        notificationManager.notify(0, builder.build())
    }
}

And in the manifest.xml:

 <service
            android:name=".MyFirebaseInstanceId">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
 </service>

I don’t think the problem is with the generated token but this is how I generate my token:

FirebaseInstanceId.getInstance().instanceId.addOnCompleteListener { p0 ->
            if (p0.isSuccessful){
                token = p0.result?.token.toString()
            }
        }

Why is the other phone not receiving notifications?

How to&Answers: