要保持FirebaseMessagingService的活动状态,即使应用程序未运行,并显示具有数据有效载荷的通知,可以按照以下步骤进行操作:
implementation 'com.google.firebase:firebase-messaging:22.0.0'
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
// 处理接收到的消息
if (remoteMessage.getData().size() > 0) {
// 获取数据有效载荷
String payload = remoteMessage.getData().get("payload");
// 显示通知
showNotification(payload);
}
}
private void showNotification(String payload) {
// 创建通知
// 可以使用NotificationCompat.Builder或自定义通知视图
// 这里只是一个简单的示例
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "channel_id")
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("通知标题")
.setContentText(payload)
.setAutoCancel(true);
// 显示通知
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(1, builder.build());
}
}
现在,当您的应用程序处于活动状态时,FirebaseMessagingService将接收到来自Firebase Cloud Messaging的消息,并显示具有数据有效载荷的通知。即使应用程序未运行,FirebaseMessagingService也将在收到消息时自动启动并显示通知。