Firebase可扩展通知当应用在后台时显示图像

Fco*_*cia 28 android background push-notification firebase-cloud-messaging

我正在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"
}
Run Code Online (Sandbox Code Playgroud)

要渲染的图像取自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());
Run Code Online (Sandbox Code Playgroud)

但是,在后台,甚至没有执行该服务.在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>
Run Code Online (Sandbox Code Playgroud)

我的问题不是LargeIcon或者SmallIcon显示大局.

感谢您的支持.

Die*_*ini 18

FCM notification messages不支持largeIcon或bigPicture.

如果你在后台需要它们,你可以使用FCM data message.

对于数据消息,onMessageReceived(message)始终调用该方法,因此您可以使用该message.getData()方法并创建自定义通知.

在此处详细了解通知消息与数据消息:https: //firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages

  • onMessageReceived(message)不在后台调用 (13认同)
  • 仅当应用程序位于前台时才调用onMessageReceived(message). (8认同)
  • 你们所有人都是正确的.当我使用firebase控制台发送消息时,我遇到了完全相同的问题.当app处于后台或被杀时,onMessageReceived不会调用.但我发送使用API​​ onMessageReceived总是被调用.我为Chrome下载了Advanced Rest客户端并开始发送通知数据.每次调用onMessageReceived.感谢以下教程http://androidbash.com/firebase-push-notification-android/ (3认同)
  • 是的,@ Krishan是正确的。一旦找到正确的位置,文档就会很清楚。当FCM消息包含“通知”有效负载,并且应用程序处于后台时,则不会调用onMessageReceived。如果它包含“数据”有效负载,那么即使它在后台(如果被杀死或未运行,也将被启动),然后调用onMessageReceived,它会被*调用。这是官方说明(应该包含在答案中):https://firebase.google.com/docs/cloud-messaging/android/receive (2认同)
  • 在后台查看此帖子以获取图像通知https://sureshsala.blogspot.in/2018/01/firebase-push-notification-with-image.html (2认同)

Arp*_*tel 8

请参阅我的FirebaseMessagingService

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "FirebaseMessageService";
    Bitmap bitmap;

    /**
     * Called when message is received.
     *
     * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
     */
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // There are two types of messages data messages and notification messages. Data messages are handled
        // here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
        // traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
        // is in the foreground. When the app is in the background an automatically generated notification is displayed.
        // When the user taps on the notification they are returned to the app. Messages containing both notification
        // and data payloads are treated as notification messages. The Firebase console always sends notification
        // messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
        //
        Log.d(TAG, "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

        //The message which i send will have keys named [message, image, AnotherActivity] and corresponding values.
        //You can change as per the requirement.

        //message will contain the Push Message
        String message = remoteMessage.getData().get("message");
        //imageUri will contain URL of the image to be displayed with Notification
        String imageUri = remoteMessage.getData().get("image");
        //If the key AnotherActivity has  value as True then when the user taps on notification, in the app AnotherActivity will be opened. 
        //If the key AnotherActivity has  value as False then when the user taps on notification, in the app MainActivity will be opened. 
        String TrueOrFlase = remoteMessage.getData().get("AnotherActivity");

        //To get a Bitmap image from the URL received
        bitmap = getBitmapfromUrl(imageUri);

        sendNotification(message, bitmap, TrueOrFlase);

    }


    /**
     * Create and show a simple notification containing the received FCM message.
     */

    private void sendNotification(String messageBody, Bitmap image, String TrueOrFalse) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("AnotherActivity", TrueOrFalse);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setLargeIcon(image)/*Notification icon image*/
                .setSmallIcon(R.drawable.firebase_icon)
                .setContentTitle(messageBody)
                .setStyle(new NotificationCompat.BigPictureStyle()
                        .bigPicture(image))/*Notification with Image*/
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }

    /*
    *To get a Bitmap image from the URL received
    * */
    public Bitmap getBitmapfromUrl(String imageUrl) {
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap bitmap = BitmapFactory.decodeStream(input);
            return bitmap;

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

参考这里


Aru*_*run 6

如果您的问题与显示大图像有关,即如果您从 firebase 控制台发送带有图像的推送通知,并且仅当应用程序在前台时才显示图像。这个问题的解决方案是发送一个只有数据字段的推送消息。

{ "data": { "image": "https://static.pexels.com/photos/4825/red-love-romantic-flowers.jpg", "message": "Firebase Push Message Using API" "AnotherActivity": "True" }, "to" : "device id Or Device token" }
Run Code Online (Sandbox Code Playgroud)

这绝对可以解决问题。


Ben*_*rad 5

包含通知和数据负载的消息(例如使用 Postman 发送的示例)会由 FCM 库自动显示给最终用户设备。这不包括(大)图像。

我想你有两种可能:

  1. 尝试拉什米·贾恩的建议。但是,如果 Firebase 库更新(以及消息处理的实现),此解决方案现在可以工作,明天就停止工作

  2. 使用 Postman 发送数据消息。因此,您可能不会在 JSON 中填写通知对象,因此它可能如下所示:

    {
      "message": {
        "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
        "data":{    
          "title" : "Awesome title",
          "body"  : "Your awesome push notification body",
          "image"  : "your_image_url"
        }
      }
    }
    
    Run Code Online (Sandbox Code Playgroud)

我更喜欢第二种选择。祝你好运!


gat*_*tti 5

如果某些地方在2019年登陆,您只需在通知对象中添加一个图像字段即可:

    {
        notification: {
            title: title,
            body: body,
            image: "http://path_to_image"
        },
        data: {
            click_action: "FLUTTER_NOTIFICATION_CLICK",
            your_data: ...,
        },
        token: token
    }
Run Code Online (Sandbox Code Playgroud)

我已经在Android上使用Flutter对其进行了测试,并且我认为它可以在本机Android上运行,因为它们可能都使用相同的本机SDK。