我正在使用 Firebase 云消息传递构建 Android 应用程序。 我的应用程序可以从 FCM 控制台接收消息。 但是,它无法从 python 接收,尽管响应很好。 你能给我一些建议吗?
class fbMessaging():
def __init__(self):
cred = credentials.Certificate('./env/firebase.json')
firebase_admin.initialize_app(cred)
def send_to_device(self, text, token):
message = messaging.Message(
data = {
'title': 'test',
'body': text,
},
token = token,
)
response = messaging.send(message)
return response
def main():
fm = fbMessaging()
res = fm.send_to_device('test', 'MY CORRECT TOKEN')
print(res)
onMessageRecieved 在这里
override fun onMessageReceived(message: RemoteMessage?) {
val from = message!!.from
val data = message.data
Log.d(TAG, "from:" + from!!)
Log.d(TAG, "data:$data")
}
打印的回复如下。
项目/匹配-XXXXX/消息/0:1554291593xxxxxx%43f99108f9xxxxxx
最佳答案
使用 Firebase Cloud Messaging ,您可以发送通知负载或数据负载或两者。
通知负载包含 title - 通知标题 body - 通知正文
key 名称是固定的,不能更改。
Data Payload,另一方面,只是一个键值对,您可以发送任何以字符串类型作为其值的键名。
FCM 行为:
根据应用程序是在前台还是后台以及通知负载或数据负载或两者的存在,应用程序中的不同组件接收 FCM 消息。
根据文档处理 FCM 通知,
Notification messages delivered when your app is in the background. In this case, the notification is delivered to the device’s system tray. A user tap on a notification opens the app launcher by default.
Messages with both notification and data payload, when received in the background. In this case, the notification is delivered to the device’s system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.
此行为已在 Receive Messages Section 中进行了清楚的解释。 .
如您所见,如果仅在单独发送通知负载的情况下,您不必构建通知 UI。否则,你有 create the Notification UI当 onMessageReceived
被调用时。
使用 Python:
通知负载示例:
message = messaging.Message(
notification=messaging.Notification(
title='This is a Notification Title',
body='This is a Notification Body',
),
token=registration_token,
)
数据负载示例:
message = messaging.Message(
data={
'score': '850',
'time': '2:45',
},
token=registration_token,
两者:
message = messaging.Message(
notification=messaging.Notification(
title='This is a Notification Title',
body='This is a Notification Body',
),
data={
'score': '850',
'time': '2:45',
},
token=registration_token,
关于android - 我的 android 应用程序无法从 python 接收 fcm 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55494702/