Android 应用程序关闭时 FCM 推送通知不起作用

phpAndroid

1个回答

写回答

Amourving

2025-07-02 09:05

+ 关注

Android
Android

标题:解决 Android 应用程序关闭时 FCM 推送通知不起作用的方法

在开发 Android 应用程序时,我们通常会使用 FCM(Firebase 云消息传递)来实现推送通知功能。然而,有时候我们会遇到一个问题,即当应用程序关闭时,FCM 推送通知无法正常工作。本文将介绍一种解决这个问题的方法,并提供相应的代码示例。

问题描述

在一些情况下,当用户关闭了应用程序或者应用程序处于后台运行时,FCM 推送通知可能无法准确地传递给设备。这导致用户无法及时收到重要的消息或通知,影响了应用程序的用户体验。

解决方案

为了解决这个问题,我们可以使用后台服务来监听 FCM 推送通知,并确保即使应用程序关闭或者处于后台运行,通知仍然可以被接收和处理。

以下是一个使用后台服务解决 FCM 推送通知无法工作的示例代码:

Java

public class MyFirebaseMessagingService extends FirebaseMessagingService {

@Override

public void onMessageReceived(RemoteMessage remoteMessage) {

// 处理接收到的消息

if (remoteMessage.getNotification() != null) {

// 获取通知标题和内容

String title = remoteMessage.getNotification().getTitle();

String body = remoteMessage.getNotification().getBody();

// 在这里处理通知,例如显示通知栏或者执行其他操作

showNotification(title, body);

}

}

private void showNotification(String title, String body) {

// 创建通知

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "channel_id")

.setSmallIcon(R.drawable.notification_icon)

.setcontentTitle(title)

.setcontentText(body)

.setPriority(NotificationCompat.PRIORITY_DEFAULT);

// 显示通知

NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

notificationManager.notify(0, builder.build());

}

}

public class MyFirebaseInstanceIdService extends FirebaseInstanceIdService {

@Override

public void onTokenRefresh() {

// 获取设备的 FCM token

String token = FirebaseInstanceId.getInstance().getToken();

// 在这里处理 token,例如发送给服务器等

}

}

实现步骤

要在应用程序中实现后台服务来监听 FCM 推送通知,可以按照以下步骤进行操作:

1. 创建一个继承自 FirebaseMessagingService 的类,并重写 onMessageReceived 方法。在这个方法中,可以获取到接收到的推送通知的信息,例如标题和内容。

2. 在 onMessageReceived 方法中,可以根据需要进行通知的处理,比如显示通知栏或者执行其他操作。

3. 创建一个继承自 FirebaseInstanceIdService 的类,并重写 onTokenRefresh 方法。在这个方法中,可以获取设备的 FCM token,并进行相应的处理,例如发送给服务器

4. 在 AndroidManifest.XML 文件中注册这两个服务,并添加相应的权限声明。

通过使用后台服务来监听 FCM 推送通知,即使应用程序关闭或者处于后台运行,我们仍然可以确保通知能够准确地传递给设备。这样可以提升应用程序的用户体验,确保用户能够及时收到重要的消息和通知。

希望本文提供的解决方案和示例代码能够帮助到开发者解决 Android 应用程序关闭时 FCM 推送通知不起作用的问题。

举报有用(4分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号