如何在我的 Android activity 中实现 FCM onMessageReceived() 侦听器

How to implement FCM onMessageReceived() listener in my Android activity

我有一个 PyFCM 服务器通过 Firebase (FCM) 向我的简单 android 应用程序发送通知。我已经测试过,当应用程序在后台 运行 时,托盘中会定期显示通知消息,没问题。我现在想在我的应用程序中接收数据消息并在发生这种情况时触发应用程序功能。我的理解是 onMessageReceived() 在收到数据消息时触发,但我不确定如何在我的代码中正确实现此侦听器。

documentation 状态:

By overriding the method FirebaseMessagingService.onMessageReceived, you can perform actions based on the received RemoteMessage object and get the message data:

这是什么意思?我看到这个 onMessageReceived() 在一个名为 MyFirebaseMessagingService.java 的文件中。这个文件去哪里了?

假设我的 MainActivity.java 中有一个函数 getLocation(),获取传入 FCM 数据消息以触发我的 getLocation() 函数的确切步骤是什么?我很难找到具体的例子。

onMessageReceived 可能会在您的应用未在用户设备上激活时被调用。因此,它在服务中运行。

第一次提到是在documentation section on accessing the device registration token. But most explanation of how to set this up is under the section on handling messages in the documentation.

我一直在做更多的研究,并且能够解决我的问题。我了解到 FCM 作为服务运行(与我的 activity 并行),但它并不真正与我的 activity 通信,至少不是直接通信。这使得从 MainActivity.java 中调用 getLocation() 成为一个问题。我能够通过 LocalBroadcastManager.

解决这个问题

示例 FCM 服务 (MyFirebaseMessagingService.java) 确实与 MainActivity.java 位于同一文件夹中,或多或少保持原样(当然,更改包名称)。但是,要启动该服务,我必须将其添加到我的应用程序清单文件中。

这就是我的问题所在;我没有在我的清单文件中的正确位置添加服务。它应该看起来像:

<?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>