当应用程序在后台或被杀死时,图像未显示在推送通知中? [英] Image not showing in push notification when app is in background or killed?

查看:55
本文介绍了当应用程序在后台或被杀死时,图像未显示在推送通知中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 React Native 开发一个应用程序,想要在应用程序处于后台或被终止时在推送通知中显示图像.当应用程序处于前台时,它运行良好,但在后台只显示标题和消息,但不显示图像.对于推送通知,我使用 react-native-firebase 来实现这一点.

bgMessaging.js 中的代码

从'react-native-firebase'导入firebase;从react-native-firebase"导入类型 { RemoteMessage };导出默认异步消息 =>{返回 Promise.resolve();};

index.js 中的代码

从'./bgMessaging'导入bgMessaging;AppRegistry.registerComponent(appName, () => App);AppRegistry.registerHeadlessTask('RNFirebaseBackgroundMessage', () => bgMessaging);

<块引用>

bgMessaging.js 中的代码负责应用在后台时的推送

为了在应用程序处于前台时显示图像,我使用了以下代码:-

async createNotificationListeners() {/** 在前台收到特定通知时触发* */this.notificationListener = firebase.notifications().onNotification((notification) => {const { 标题,正文} = 通知;console.log('onNotification:');const channel = new firebase.notifications.Android.Channel('fcm_default_channel','SAT VS ACT',firebase.notifications.Android.Importance.Max).setDescription('频道的自然描述');firebase.notifications().android.createChannel(channel);this.unsubscribeFromNotificationListener = firebase.notifications().onNotification((notification) => {if (Platform.OS === 'android') {console.log('背景');const localNotification = new firebase.notifications.Notification({声音:'默认',show_in_foreground: 真,}).setNotificationId(notification.notificationId).setTitle(notification.title).setSubtitle(notification.subtitle).setBody(notification.body).setData(notification.data).android.setChannelId('fcm_default_channel')//例如您在上面选择的 ID//.android.setSmallIcon('ic_stat_notification')//在 Android Studio 中创建这个图标.android.setColor('#000000')//可以在这里设置颜色.android.setBigPicture('https://picsum.photos/200/300').android.setPriority(firebase.notifications.Android.Priority.High);firebase.notifications().displayNotification(localNotification).catch(err => console.error(err));}});});/** 如果您的应用程序在后台,您可以在点击/点击/打开通知时进行监听,如下所示:* */this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen) => {const { title, body } = notificationOpen.notification;console.log('onNotificationOpened:');Alert.alert(标题,正文)});/** 如果您的应用程序已关闭,您可以检查它是否是通过点击/点击/打开的通知打开的,如下所示:* */const notificationOpen = 等待 firebase.notifications().getInitialNotification();如果(通知打开){const { title, body } = notificationOpen.notification;console.log('getInitialNotification:');Alert.alert(标题,正文)}/** 在前台仅针对数据有效负载触发* */this.messageListener = firebase.messaging().onMessage((message) => {//处理数据消息console.log("JSON.stringify:", JSON.stringify(message));});}

暂时使用http://pushtry.com/发送推送通知.推送的 json:-

<代码> {"to":"",通知":{"title":"工作良好","body":"考试 vlo hbe na tor",},优先级":高"}

我对本机反应很陌生,感谢任何形式的帮助.

解决方案

如果您的负载包含 notification 键,则您的应用程序将仅在您的应用程序处于活动状态/在前台时自行处理推送消息,如它们被传送到您的 onMessageReceived 处理程序.否则(因此它在后台或被杀死),FCM 会使用您放入通知键负载的值来处理为您显示通知.

如果您的负载仅包含一个 data 键,您的应用将自行处理所有推送消息.它们都传送到您的 onMessageReceived 处理程序.

请参阅此参考:https://stackoverflow.com/a/37876727/3037523

I am developing an app in React native, want to show Image in push notification when the app is in background or killed. When the app is in foreground it is doing fine but in background only title and message is showing but not the image. For push notification I am using react-native-firebase to achieve this.

Code in bgMessaging.js

import firebase from 'react-native-firebase';
import type { RemoteMessage } from 'react-native-firebase';

export default async message => {
    return Promise.resolve();
};

Code in index.js

import bgMessaging from './bgMessaging';
AppRegistry.registerComponent(appName, () => App);
AppRegistry.registerHeadlessTask('RNFirebaseBackgroundMessage', () => bgMessaging);

Code in bgMessaging.js is responsible for the push when the app is in background

To bring the image when the app is in foreground I used the code below:-

async createNotificationListeners() {
    /*
    * Triggered when a particular notification has been received in foreground
    * */
    this.notificationListener = firebase.notifications().onNotification((notification) => {
      const { title, body } = notification;
      console.log('onNotification:');
      const channel = new firebase.notifications.Android.Channel(
        'fcm_default_channel',
        'SAT VS ACT',
        firebase.notifications.Android.Importance.Max
      ).setDescription('A natural description of the channel');
        firebase.notifications().android.createChannel(channel);
        this.unsubscribeFromNotificationListener = firebase.notifications().onNotification((notification) => {
            if (Platform.OS === 'android') {
              console.log('background');
              const localNotification = new firebase.notifications.Notification({
                  sound: 'default',
                  show_in_foreground: true,
                })
                .setNotificationId(notification.notificationId)
                .setTitle(notification.title)
                .setSubtitle(notification.subtitle)
                .setBody(notification.body)
                .setData(notification.data)
                .android.setChannelId('fcm_default_channel') // e.g. the id you chose above
                //.android.setSmallIcon('ic_stat_notification') // create this icon in Android Studio
                .android.setColor('#000000') // you can set a color here
                .android.setBigPicture('https://picsum.photos/200/300')
                .android.setPriority(firebase.notifications.Android.Priority.High);

              firebase.notifications()
                .displayNotification(localNotification)
                .catch(err => console.error(err));

            } 
          });
    });


    /*
    * If your app is in background, you can listen for when a notification is clicked / tapped / opened as follows:
    * */
    this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen) => {
      const { title, body } = notificationOpen.notification;
      console.log('onNotificationOpened:');
      Alert.alert(title, body)
    });

    /*
    * If your app is closed, you can check if it was opened by a notification being clicked / tapped / opened as follows:
    * */
    const notificationOpen = await firebase.notifications().getInitialNotification();
    if (notificationOpen) {
      const { title, body } = notificationOpen.notification;
      console.log('getInitialNotification:');
      Alert.alert(title, body)
    }
    /*
    * Triggered for data only payload in foreground
    * */
    this.messageListener = firebase.messaging().onMessage((message) => {
      //process data message
      console.log("JSON.stringify:", JSON.stringify(message));
    });
  }

For the time being using http://pushtry.com/ to send push notification. The json for the push:-

 {
    "to":"<FCM_TOKEN>",
"notification":
    {
        "title":"Working Good",
"body":"Exam vlo hbe na tor",
    },
"priority":"high"
}

I am very new to react native, any kind of help is appreciated.

解决方案

If your payload contains a notification key, your app will handle push messages itself only if your app is active/in the foreground as they are delivered to your onMessageReceived handler. Otherwise (so it's in the background, or killed), FCM handles showing the notification for you by using the values you put into the notification key payload.

If your payload contains only a data key, your app will handle all push messages itself. They are all delivered to your onMessageReceived handler.

See this reference: https://stackoverflow.com/a/37876727/3037523

这篇关于当应用程序在后台或被杀死时,图像未显示在推送通知中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆