如何在应用后台时为Firebase通知显示自定义UI?
Firebase自定义通知UI后台不生效的解决方案
我之前也碰到过一模一样的问题——用Firebase做自定义RemoteViews通知,前台显示正常,一到后台就变成系统默认样式,折腾了好久才搞明白原因,现在把解决方法分享给你:
问题根源
Firebase的推送分为两种类型:
- 通知消息(Notification Payload):当APP在后台时,这条消息会被Android系统直接接管,不会触发
onMessageReceived方法,自然也就用不上你自定义的UI了;只有APP在前台时,才会走到你写的逻辑里。 - 数据消息(Data Payload):不管APP是前台还是后台,这条消息都会被
onMessageReceived接收,完全由你的代码来处理展示逻辑。
你之前的代码只处理了remoteMessage.getNotification()(也就是通知消息),后台时根本没走这段逻辑,系统直接用默认样式显示了。
解决步骤
切换为数据消息推送
发送推送的时候,要把内容放在data字段里,而不是notification字段。比如调用Firebase API的请求体应该是这样的:{ "to": "目标设备的FCM令牌", "data": { "title": "你的通知标题", "body": "你的通知内容" } }修改
MyFirebaseMessagingService代码
改成处理data字段的内容,同时要注意设置setCustomContentView和setCustomBigContentView,确保折叠和展开状态都显示自定义UI:public class MyFirebaseMessagingService extends FirebaseMessagingService { private static final String TAG = "Mehdi"; @Override public void onMessageReceived(RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); // 处理数据消息,前后台都会触发 if (!remoteMessage.getData().isEmpty()) { String title = remoteMessage.getData().get("title"); String body = remoteMessage.getData().get("body"); // 初始化自定义布局 RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.payam_notification_layout); contentView.setTextViewText(R.id.payam, body); String channelId = "Default"; NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, channelId) .setSmallIcon(R.drawable.status_icon_delivered) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.icon)) .setSound(Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.notification)) .setCustomContentView(contentView) // 折叠状态的自定义UI .setCustomBigContentView(contentView) // 展开状态的自定义UI .setAutoCancel(true); NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel(channelId, "Default channel", NotificationManager.IMPORTANCE_DEFAULT); manager.createNotificationChannel(channel); } manager.notify(0, mBuilder.build()); } } }检查自定义布局兼容性
你的payam_notification_layout只能用系统原生控件(比如TextView、ImageView、ProgressBar这些),不能用自定义View,否则后台可能还是会 fallback 到默认样式。
这样修改之后,不管APP是前台还是后台,都能正常显示你自定义的通知UI啦!
内容的提问来源于stack exchange,提问作者X Fa
相关产品推荐
相关产品推荐

