FCM应用后台/进程终止时无法解析JSON消息体及显示自定义图片求助
FCM后台/进程终止时无法解析JSON消息体及显示自定义图片的解决方案
核心原因
FCM的通知消息(带notification字段)在应用后台/进程终止时,会由系统直接接管展示,不会触发onMessageReceived();只有数据消息(仅含data字段)或应用前台时,onMessageReceived()才会被调用。你的问题本质是混淆了两种消息类型的处理逻辑。
解决方案
方案1:发送纯数据消息(推荐)
完全移除notification字段,所有内容放在data中。这种方式下,无论应用处于前台、后台还是进程终止,都会触发onMessageReceived(),你可以完全自定义通知的展示逻辑。
示例发送Payload:
{ "to": "目标设备Token", "data": { "title": "你的通知标题", "message_body": "{\"content\":\"自定义内容\",\"image_url\":\"https://your-domain.com/custom-image.jpg\"}" } }
在FirebaseMessagingService中处理:
@Override public void onMessageReceived(RemoteMessage remoteMessage) { // 解析data中的JSON消息体 String messageBody = remoteMessage.getData().get("message_body"); JSONObject jsonBody = new JSONObject(messageBody); // 获取自定义图片URL和其他字段 String imageUrl = jsonBody.getString("image_url"); String content = jsonBody.getString("content"); String title = remoteMessage.getData().get("title"); // 构建自定义通知 NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "CHANNEL_ID") .setSmallIcon(R.drawable.ic_notification) .setContentTitle(title) .setContentText(content) .setPriority(NotificationCompat.PRIORITY_DEFAULT); // 异步加载自定义图片到通知 Glide.with(this) .asBitmap() .load(imageUrl) .into(new CustomTarget<Bitmap>() { @Override public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) { builder.setLargeIcon(resource); // 显示通知 NotificationManagerCompat notificationManager = NotificationManagerCompat.from(MyFirebaseMessagingService.this); notificationManager.notify(1, builder.build()); } @Override public void onLoadCleared(@Nullable Drawable placeholder) {} }); }
方案2:混合消息场景下的兼容处理
如果必须保留notification字段,后台时系统会默认展示通知,data字段会附加到点击通知启动的Intent中。你可以在应用启动页/主Activity中获取并解析:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 获取通知携带的data数据 Intent intent = getIntent(); if (intent != null && intent.getExtras() != null) { String messageBody = intent.getExtras().getString("message_body"); if (messageBody != null) { // 解析JSON并处理业务逻辑 JSONObject jsonBody = new JSONObject(messageBody); // ... } } } // 处理应用在前台时的通知跳转 @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); // 重复上述解析逻辑 }
注意:这种方式只能在用户点击通知进入应用后才能处理数据,无法在后台自动解析或替换系统默认通知的图片,仅作为兼容方案。
关键注意事项
- 确保
FirebaseMessagingService已在AndroidManifest.xml中正确注册:<service android:name=".MyFirebaseMessagingService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service> - 自定义图片需符合Android通知的尺寸要求(大图标建议192x192dp),避免加载失败;使用图片加载库(如Glide)异步加载,避免阻塞主线程。
内容的提问来源于stack exchange,提问作者Am XYZ
相关产品推荐
相关产品推荐

