Firebase 可扩展通知在应用程序处于后台时显示图像

新手上路,请多包涵

我正在 Android 中实现 FCM 通知,但通知如何根据应用状态(后台与前台)而有所不同?

查看通知图片

我正在使用带有 Postman 的 FCM API 发送通知,这是通知结构:

 { "notification": {
      "title": "Notification title",
      "body": "Notification message",
      "sound": "default",
      "color": "#53c4bc",
      "click_action": "MY_BOOK",
      "icon": "ic_launcher"
   },
   "data": {
       "main_picture": "URL_OF_THE_IMAGE"
   },
   "to" : "USER_FCM_TOKEN"
}

要渲染的图像取自 data.main_picture

我已经实现了自己的 FirebaseMessagingService 这使得通知在前台状态下完美显示。通知代码如下:

 NotificationCompat.BigPictureStyle notiStyle = new NotificationCompat.BigPictureStyle();
notiStyle.setSummaryText(messageBody);
notiStyle.bigPicture(picture);

Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setLargeIcon(bigIcon)
            .setContentTitle(title)
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent)
            .setStyle(notiStyle); code here

NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());

然而,在后台,该服务甚至没有被执行。在 AndroidManifest.xml 中,Firebase 服务声明如下:

 <service
    android:name=".MyFirebaseMessagingService">
  <intent-filter>
    <action android:name="com.google.firebase.MESSAGING_EVENT"/>
  </intent-filter>
</service>

<service
    android:name=".MyFirebaseInstanceIDService">
  <intent-filter>
    <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
  </intent-filter>
</service>

我的问题不是 LargeIconSmallIcon 而是显示全局。

谢谢你的支持。

原文由 Fco. Javier Hernandez Garcia 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 533
1 个回答

要在前台显示来自推送通知的图像,

首先,您必须在后端的 android 部分附加 imageUrl 字段,您可以在以下位置找到有关此概念的更多信息:

Firebase 发送 URL 图片

其次,您可以在“onMessageReceived”函数上检索该字段,您可以通过以下方式访问该字段:

 remoteMessage.notification?.imageUrl

第三,这是一个 Uri,里面有一个 Url,你可以通过以下方式访问 url:

 val url = URL(imageUrl?.toString())

四、必须下载内容并放入位图:

 private fun getBitmapfromUrl(imageUrl: Uri?): Bitmap? {
    return try {
        val url = URL(imageUrl?.toString())
        val connection: HttpURLConnection = url.openConnection() as HttpURLConnection
        connection.setDoInput(true)
        connection.connect()
        val input: InputStream = connection.getInputStream()
        BitmapFactory.decodeStream(input)
    } catch (e: Exception) {
        // TODO Auto-generated catch block
        e.printStackTrace()
        null
    }
}

五、将位图附加到通知中:

 .setLargeIcon(imageBitmap)

萨卢多斯。

原文由 Adrian Yama Yama 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题