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

时间:2016-07-21 12:17:53

标签: android background push-notification firebase-cloud-messaging

我正在Android中实施FCM通知,但根据应用状态(背景与前景)的不同,通知有何不同?

see notifications image

我正在使用带有邮递员的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,而是展示了大局。

感谢您的支持。

12 个答案:

答案 0 :(得分:15)

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

答案 1 :(得分: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;

        }
    }
}

REFERENCE HERE

答案 2 :(得分:3)

如果您的问题与显示大图像有关,即您是否使用来自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" }

这绝对解决了这个问题。

答案 3 :(得分:2)

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

我想您有两种可能:

  1. 尝试Rashmi Jain的建议。但是,如果Firebase库得到了更新(从而实现了消息处理的实现),则该解决方案现在可以立即使用,明天就可以停止使用。

  2. 与邮递员发送数据消息。因此,您可能无法在JSON中填充通知对象,因此它看起来可能像这样:

    {
      "message": {
        "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
        "data":{    
          "title" : "Awesome title",
          "body"  : "Your awesome push notification body",
          "image"  : "your_image_url"
        }
      }
    }
    

我希望第二个选项。祝你好运!

答案 4 :(得分:1)

“数据”键必须位于“推送通知”捆绑包中。

除了以上答案外, 如果您正在使用 FCM控制台测试推送通知,则键和对象不会添加到“推送通知”捆绑包中。因此,当应用程序处于后台或被终止运行时,您将不会收到详细的推送通知。

在这种情况下,您必须选择后端管理控制台来测试App后台情况。

在这里,您将在推包中添加“数据”键。因此,详细的推送将按预期显示。 希望对您有所帮助。

答案 5 :(得分:0)

如果您希望应用系统托盘中只有一个通知,那么以下解决方案可以解决问题,直到FCM提出正确的解决方案。

  1. 从清单中删除MyFirebaseMessagingService。

    <service android:name=".MyFirebaseMessagingService">   <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT"/>   </intent-filter> </service>
    
  2. MyGcmReceiver扩展GcmReceiver类并修改通知逻辑。
  3. 在清单

    中添加MyGcmReceiver
        <receiver
        android:name=".MyGcmReceiver"
        android:exported="true"
        android:permission="com.google.android.c2dm.permission.SEND">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <category android:name="package_name" />
        </intent-filter>
    </receiver>
    
  4. 在通知通知之前取消所有通知。 (否则也是firebase,当app在后台时显示通知)

答案 6 :(得分:0)

您可以使用此休息客户端工具发送消息。使用此工具您也可以在后台和前台向客户端应用程序发送消息。 要使用API​​发送消息,您可以使用名为AdvancedREST Client的工具,它的chrome扩展名,并使用以下参数发送消息。

Rest客户端工具链接:https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo

使用此网址: - https://fcm.googleapis.com/fcm/send Content-Type:application / json授权:key =您的服务器密钥From或Authoization密钥(参见下面的参考资料)

{“data”:{“image”:“https://static.pexels.com/photos/4825/red-love-romantic-flowers.jpg”,“message”:“使用API​​的Firebase推送消息”“AnotherActivity”:“True”},“to”:“设备ID或设备令牌“}

可以通过访问Google开发人员控制台并单击项目左侧菜单上的“凭据”按钮来获取授权密钥。在列出的API密钥中,服务器密钥将是您的授权密钥。

你需要将接收者的tokenID放在使用API​​发送的POST请求的“to”部分。

而这段安卓代码     //消息将包含推送消息

    String message = remoteMessage.getData().get("message1");

    //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 MainActivity2 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);

答案 7 :(得分:0)

从Firebase控制台发送大图通知: 适用于后台应用程序和前台应用程序

而不是onMessageReceived,覆盖zzm()的{​​{1}}并从此处创建自定义通知

FirebaseMessagingService

答案 8 :(得分:0)

例如,如果您要发送推送通知,则获取数据中的所有必需内容而不是通知,例如

{
   "data": {
       "main_picture": "URL_OF_THE_IMAGE",
       "title": "Notification title",
      "click_action": "MY_BOOK", 
      "color": "#53c4bc", 
   },
   "to" : "USER_FCM_TOKEN"
}

删除通知对象并从数据对象获取所有值。

希望它对您有用。

答案 9 :(得分:0)

如果某些地方将于2019年登陆,您只需在通知对象中添加一个 image 字段:

    {
        notification: {
            title: title,
            body: body,
            image: "http://path_to_image"
        },
        data: {
            click_action: "FLUTTER_NOTIFICATION_CLICK",
            your_data: ...,
        },
        token: token
    }

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

答案 10 :(得分:0)

更新2019年8月。

[浪费了几天是因为py不支持通知的最新更改]

只需将 image = url 添加到您的通知对象中。

它可在本机Android中运行。只需将class CustomCell: UICollectionViewCell { override func awakeFromNib() { super.awakeFromNib() self.layer.cornerRadius = 30 self.clipsToBounds = true } } 添加到通知对象中即可。另外请注意,在Python库中,image字段不存在。 [截至8月19日] https://github.com/firebase/firebase-admin-python

我使用了PHP,并且该库https://github.com/kreait/firebase-php/ 它超级简单,更重要的是,当应用程序在后台或已被杀死时,它可用于大图像通知。

代码:

collectionView(_:cellForItemAt:)

答案 11 :(得分:0)

推送5完全取决于接收到的推送请求,并且设备功能(例如某些设备的电池军刀)会影响我们所有的内容,即url图像而不是推送请求中的实际图像,因此设备应具有下载图像的能力,而android / apk显示图像和Firebase或APNS