这是我的清单:
<service android:name=".fcm.PshycoFirebaseMessagingServices"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service> <service android:name=".fcm.PshycoFirebaseInstanceIDService"> <intent-filter> <action android:name="com.google.firebase.INSTANCE_ID_EVENT" /> </intent-filter> </service>
当应用程序在后台并收到通知时,默认通知会出现并且不会运行我的onMessageReceived.
onMessageReceived
这是我的onMessageReceived代码。如果我的应用程序在前台运行,而不是在后台运行,则会调用此方法。当应用程序也在后台时,如何运行此代码?
// [START receive_message] @Override public void onMessageReceived(RemoteMessage remoteMessage) { // TODO(developer): Handle FCM messages here. // If the application is in the foreground handle both data and notification messages here. // Also if you intend on generating your own notifications as a result of a received FCM // message, here is where that should be initiated. See sendNotification method below. data = remoteMessage.getData(); String title = remoteMessage.getNotification().getTitle(); String message = remoteMessage.getNotification().getBody(); String imageUrl = (String) data.get("image"); String action = (String) data.get("action"); Log.i(TAG, "onMessageReceived: title : "+title); Log.i(TAG, "onMessageReceived: message : "+message); Log.i(TAG, "onMessageReceived: imageUrl : "+imageUrl); Log.i(TAG, "onMessageReceived: action : "+action); if (imageUrl == null) { sendNotification(title,message,action); } else { new BigPictureNotification(this,title,message,imageUrl,action); } } // [END receive_message]
FCM(Firebase Cloud Messaging)中有两种类型的消息:
onMessageReceived()
注意: Firebase 团队尚未开发可发送data-messages到您的设备的 UI。您应该使用您的服务器发送此类型!
data-messages
为此,您必须向POST以下 URL 执行请求:
POST
POST https://fcm.googleapis.com/fcm/send
Content-Type
application/json
Authorization
key=<your-server-key>
{ "to": "/topics/my_topic", "data": { "my_custom_key": "my_custom_value", "my_custom_key2": true } }
{ "data": { "my_custom_key": "my_custom_value", "my_custom_key2": true }, "registration_ids": ["{device-token}","{device2-token}","{device3-token}"] }
注意: 确保您 没有添加 JSON 密钥notification 注意: 要获取服务器密钥,您可以在 firebase 控制台中找到它:Your project -> settings -> Project settings -> Cloud messaging -> Server Key
notification
Your project -> settings -> Project settings -> Cloud messaging -> Server Key
这是您处理收到的消息的方式:
@Override public void onMessageReceived(RemoteMessage remoteMessage) { Map<String, String> data = remoteMessage.getData(); String myCustomKey = data.get("my_custom_key"); // Manage data }