当应用程序未运行时,Android Studio 无法接受推送通知的负载。要解决此问题,您需要在应用程序中实现 FirebaseMessagingService 类以处理通知负载。在 FirebaseMessagingService 类中,您可以使用 onMessageReceived 方法来接收通知负载并执行所需的操作。以下是一个示例:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMessagingService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
// Get notification payload
String notificationTitle = remoteMessage.getNotification().getTitle();
String notificationBody = remoteMessage.getNotification().getBody();
// Get data payload
String dataValue1 = remoteMessage.getData().get("key1");
String dataValue2 = remoteMessage.getData().get("key2");
// Handle notification
sendNotification(notificationTitle, notificationBody, dataValue1, dataValue2);
}
private void sendNotification(String notificationTitle, String notificationBody, String dataValue1, String dataValue2) {
// Build notification
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "channel_id")
.setContentTitle(notificationTitle)
.setContentText(notificationBody)
.setSmallIcon(R.drawable.ic_notification)
.setAutoCancel(true);
// Handle data payload
if (dataValue1 != null && dataValue2 != null) {
// Do something with data values
}
// Show notification
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(0, notificationBuilder.build());
}
}
您还需要在 AndroidManifest.xml 文件中声明您的 FirebaseMessagingService 类,如下所示:
现在您可以在应用程序未运行时接受推送通知并处理通知负载。