Firebase 后台通知处理:让你的应用程序时刻响应
2024-03-16 12:42:41
处理 Firebase 中应用程序后台时的通知
在移动应用程序开发中,处理应用程序在后台时接收的通知是一个常见的难题。虽然 Firebase 提供了一个默认通知系统,但在后台时自定义代码可能无法执行。本文将指导你如何克服这一挑战,让你的应用程序即使在后台也能响应 Firebase 通知。
问题定义
- 当应用程序在后台时,默认通知会显示,但
onMessageReceived
代码不会执行。 - 我们的目标是让
onMessageReceived
代码在应用程序处于后台时也能执行,以处理自定义通知逻辑。
解决方案步骤
1. 启用后台消息处理
Firebase SDK 20.2.0 及更高版本支持在后台处理消息。确保在 AndroidManifest.xml
文件中启用以下权限:
<manifest ...>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<service
android:name=".fcm.PshycoFirebaseMessagingServices"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</manifest>
2. 修改 onMessageReceived
方法
更新 onMessageReceived
方法以处理后台消息。添加以下代码:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (remoteMessage.getNotification() != null) {
handleNotification(remoteMessage.getNotification());
}
}
3. 定义 handleNotification
方法
创建一个辅助方法 handleNotification
来处理后台通知:
private void handleNotification(Notification notification) {
// 从通知中提取数据
String title = notification.getTitle();
String message = notification.getText();
String action = notification.getAction();
// 处理后台通知逻辑,例如更新 UI 或显示自定义通知
// ...
}
4. 添加 FirebaseMessagingService
创建扩展自 FirebaseMessagingService
的服务类。这个类将在后台接收和处理消息:
public class PshycoFirebaseMessagingServices extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// 在这里处理后台消息
handleMessage(remoteMessage);
}
private void handleMessage(RemoteMessage remoteMessage) {
// 从消息中提取数据
// ...
// 处理后台通知逻辑
// ...
}
}
5. 更新 AndroidManifest.xml
在 AndroidManifest.xml
中,声明 PshycoFirebaseMessagingServices
服务:
<service
android:name=".fcm.PshycoFirebaseMessagingServices"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
常见问题解答
1. 在 Android 10 及更高版本上支持后台通知有什么特殊要求?
在 Android 10 及更高版本上,必须启用后台位置访问权限才能接收后台通知。
2. 如何调试后台通知?
可以使用 Firebase Logcat 过滤器来调试后台通知。在 Logcat 中,过滤消息为 FirebaseMessaging:EVENT
。
3. 如何处理来自后台通知的大型数据负载?
Firebase 提供了 FirebaseMessaging.Notification
类,允许你指定通知的标题、正文和数据负载。数据负载字段可用于存储较大数据。
4. 是否可以使用 FCM 发送优先级很高的通知?
是的,可以使用 FCM 发送优先级很高的通知。在通知数据中设置 priority
为 high
即可。
5. 如何防止 Firebase 通知显示在锁屏上?
在 AndroidManifest.xml
文件中设置 visibility
属性即可防止通知显示在锁屏上。将 visibility
设置为 SECRET
或 PRIVATE
。
结论
通过遵循这些步骤,你可以让你的应用程序在后台时接收和处理 Firebase 通知。这使你能够创建更具响应性和交互性的移动应用程序,即使在应用程序未处于活动状态时也是如此。