我正在尝试使用Firebase Cloud Messaging 进行一些操作,并且我可以使用FCM控制台通过FCM令牌向设备发送消息。我以为即使您的应用程序没有完全运行,您也可以收到这些消息。但是当我的应用程序在后台运行时,我只能收到这些消息。
我现在的问题是,当您的应用程序未运行时是否可以接收消息,如果是,我该如何完成此操作?
以下是我添加到清单的内容:
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/app_icon" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/colorAccent" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="@string/default_notification_channel_id" />
<service
android:name=".MyFirebaseInstanceIdService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
<service
android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
在课堂上:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
//if the message contains data payload
//It is a map of custom keyvalues
//we can read it easily
if(remoteMessage.getData().size() > 0){
//handle the data message here
}
//getting the title and the body
String title = remoteMessage.getNotification().getTitle();
String body = remoteMessage.getNotification().getBody();
}
}
public class MyFirebaseInstanceIdService extends FirebaseInstanceIdService{
//private Socket mSocket;
@Override
public void onTokenRefresh() {
super.onTokenRefresh();
String token = FirebaseInstanceId.getInstance().getToken();
Log.d("MyRefreshedToken", token);
storeToken(token);
}
private void storeToken(String token) {
SharedPrefManager.getInstance(getApplicationContext()).saveDeviceToken(token);
}
}
是的,当你的应用未运行时,可以使用你的onMessageReceived-方法接收消息。为此,您需要发送数据消息,也称为静默推送消息。这意味着您需要省略通知标题和正文属性,并且仅发送带有 data 属性的信息。
前任。
{
"message": {
"token":"78yadsbjbasjkdjbkasbdjkbak...",
"data": {
"Topic" : "Data message",
"Content" : "This message should be handled by onMessageReceived regardless if the app is running or not.",
}
}
}
有关更多信息,请查看 Firebase 文档中的以下页面:
- https://firebase.google.com/docs/cloud-messaging/android/receive
- https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages