I have a PyFCM server sending notifications via Firebase (FCM) to my simple android app. I have tested and get regular notification messages to appear in the tray when the app is running in the background no problem. I would now like to receive data messages in my app and trigger app functions when that happens. My understanding is that onMessageReceived()
is triggered when a data message is received, but I'm not sure how to implement this listener properly in my code.
The documentation states:
By overriding the method
FirebaseMessagingService.onMessageReceived
, you can perform actions based on the receivedRemoteMessage
object and get the message data:
What does that mean? I see that this onMessageReceived()
is in a file called MyFirebaseMessagingService.java. Where does this file go?
Say I have a function getLocation()
in my MainActivity.java, what are the exact steps to get an incoming FCM data message to trigger my getLocation()
function? I am having difficulty finding concrete examples.
I've been doing more research, and I was able to solve my problem. I learned that FCM runs as a service (in parallel to my activity), but that it doesn't really communicate with my activity, at least not directly. This makes calling getLocation()
from within MainActivity.java a problem. I was able to get around that with a LocalBroadcastManager.
The example FCM service (MyFirebaseMessagingService.java) does go in the same folder as MainActivity.java, more or less as is (changing the package name, of course). However, for the service to be initiated, I have to add it to my app manifest file.
And that's where my problem lay; I didn't add the service in the right place in my manifest file. It should look something like:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.project">
<application
.../>
<activity ...
</activity>
<service
android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
</application>
</manifest>