6
votes

La notification push ne s'affiche pas au premier plan d'Android

J'ai utilisé react-native-fcm pour la notification à distance sous Android et iPhone.

react-native-fcm

Au premier plan d'Android, je ne peux pas recevoir de notification à distance dans la barre de notification.

En arrière-plan mode Je parviens à recevoir une notification avec succès, mais ce n'est pas le cas au premier plan.

Android Manifest.xml

async componentDidMount() {
// create NotificationChannel for future use!
    FCM.createNotificationChannel({
      id: 'my_default_channel',
      name: 'Default',
      description: 'used for example',
      priority: 'high'
    });

    // initially user get InitialNotification frim the app if any pending
    FCM.getInitialNotification().then(notif => {
      console.log("getInitialNotification Notification : => ", notif);

      // if notif.targetScreen is details screen then it will redirect to details screen directly!
      if (notif && notif.targetScreen === "detail") {
        setTimeout(() => {
          this.props.navigation.navigate("Detail");
        }, 500);
      }
    });

    // added notification listener for getting any notification called below function then
    this.notificationListener =  FCM.on(FCMEvent.Notification, async (notif) =>  {
      console.log("FCMEvent.Notification Notification : => ", notif);

      if (Platform.OS === 'ios' && notif._notificationType === NotificationType.WillPresent && !notif.local_notification) {
        notif.finish(WillPresentNotificationResult.All);
        return;
      }

      // if user tap to notification bar then open app then below condition will follow up and redirect to details screen!
      if (notif.opened_from_tray) {
        if (notif.targetScreen === 'detail') {
          setTimeout(() => {
            navigation.navigate('Detail')
          }, 500)
        }
        setTimeout(() => {
          alert(`User tapped notification\n${JSON.stringify(notif)}`)
        }, 500)
      }

      // check whether app is in background or foreground for generate notification
     if (AppState.currentState !== 'background'){
        this.showLocalNotification(notif);


    });

    // getting user permission for sending notification or not ?
    try {
      let result = await FCM.requestPermissions({
        badge: true,
        sound: true,
        alert: true
      });
      console.log("Notification requestPermissions : => ", result)
    } catch (e) {
      console.error(e);
    }

    // Generating token for particular user wise send notification
    FCM.getFCMToken().then(token => {
      FCM.subscribeToTopic("channelToTopic");
      console.log("Notification token : => ", token);
      this.setState({ token: token || "" });
    });

    // Get APNSTOKEN for only ios
    if (Platform.OS === "ios") {
      FCM.getAPNSToken().then(token => {
        console.log("APNS TOKEN (getFCMToken)", token);
      });
    }
  }

  // show notification when app is in foreground and getting any new notification
  showLocalNotification = (notif) => {
    FCM.presentLocalNotification({
      channel: 'my_default_channel',
      id: new Date().valueOf().toString(),
      title: notif.fcm.title,
      body: notif.fcm.body,
      priority: "high",
      badge: 1,
      number: 1,
      ticker: "My Notification Ticker",
      auto_cancel: true,
      big_text: "Show when notification is expanded",
      sub_text: "This is a subText",
      wake_screen: true,
      group: "group",
      icon: "ic_launcher",
      ongoing: true,
      my_custom_data: "my_custom_field_value",
      lights: true,
      show_in_foreground: true
    });
  };

App.js

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.nusape">

    <application>

        <receiver android:name="com.evollu.react.fcm.FIRLocalMessagingPublisher"/>
        <receiver android:enabled="true" android:exported="true"  android:name="com.evollu.react.fcm.FIRSystemBootEventReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
                <action android:name="android.intent.action.QUICKBOOT_POWERON"/>
                <action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </receiver>

        <meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@mipmap/ic_launcher"/>
        <meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="my_default_channel"/>

        <service android:name="com.evollu.react.fcm.MessagingService" android:enabled="true" android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>

        <service android:name="com.evollu.react.fcm.InstanceIdService" android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>



       <activity android:launchMode="singleTop" android:configChanges="keyboard|keyboardHidden|orientation|screenSize" android:windowSoftInputMode="adjustResize">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <intent-filter>
                <action android:name="fcm.ACTION.HELLO" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

        </activity>
        <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
    </application>

</manifest>

Je souffre de ce problème des 2 derniers mois et je ne trouve pas de solution correcte pour la même chose que je fais tellement nouvelle tentative de résolution du problème, mais sans succès à la fin.


1 commentaires

Y a-t-il quelqu'un ici qui a la solution parfaite? pour la question. au lieu d'envoyer une notification locale?


3 Réponses :


2
votes

Conformément aux problèmes de bibliothèque répertoriés ici , vous pouvez en essayer deux choses:

  1. il suffit de passer show_in_foreground dans votre propriété data dans la notification à distance

  2. Android affiche une notification uniquement lorsque l'état de l'application est supprimé ou en arrière-plan. Pour afficher les notifications au premier plan de l'application, vous devez afficher la notification locale .

Exemple de code:

FCM.on(FCMEvent.Notification, notif => {
    if (!notif.opened_from_tray) {
        showLocalNotification();
    }
});

showLocalNotification() {
    FCM.presentLocalNotification({
      id: new Date().valueOf().toString(),         // (optional for instant notification)
      title: "Test Notification with action",      // as FCM payload
      body: "Force touch to reply",                // as FCM payload (required)
      show_in_foreground: true                     // notification when app is in foreground (local & remote)
    });
  }

Le code complet est ici


2 commentaires

J'ai une question, je développe deux applications d'abord de l'application utilisateur et ensuite des fournisseurs, dans l'application utilisateur, j'ai créé une fonction pour envoyer une commande et l'enregistrer dans la base de données en temps réel firebase t et dans la deuxième application, je viens de récupérer le données de DB avec un auditeur pour obtenir la nouvelle commande en temps réel sans actualiser l'application, donc je veux quand j'envoie une commande de l'application utilisateur à Firebase Je veux afficher une notification dans la deuxième application? Comment gérer ces


vous devez rechercher la notification en amont pour cela



2
votes

Sur quel niveau d'API testez-vous? L'API Android 26 et supérieur nécessite la création de canaux afin de recevoir des notifications au premier plan. veuillez lire ceci pour plus d'informations.

react-native-fcm est également mis à jour pour inclure également les chaînes, reportez-vous à ceci bien que la bibliothèque ne doive plus être utilisée car la bibliothèque n'est plus maintenue, une bonne alternative est react-native-firebase .


0 commentaires

6
votes

Selon le Github officiel de react-native-fcm , cette bibliothèque est dépréciée. Vous pouvez utiliser le react-native-firebase pour générer une notification. J'ai pu faire fonctionner les notifications en environ 2 heures pour Android. Si vous voulez le code, je peux le partager. Bonne chance.

Mise à jour - Désolée, je n'ai pas pu répondre plus tôt à cause de mon compte professionnel.

Voici mon code pour afficher les notifications de premier plan Android.

firebase.messaging()
        .subscribeToTopic(this.state.user.user_name)
        .then(response => console.log('response from FCM TOPIC' + response))
        .catch(error =>  console.log('error from FCM TOPIC'+ error));

        this.notificationListener = firebase.notifications().onNotification(notification => {
            let notificationMessage = notification._android._notification._data.action;
            let recordId = notification._android._notification._data.recordID;

            let { title, body } = notification;
            //  console.log('ttttt', notification)
            // notification.android.setAutoCancel(false)
            console.log(title, body, notificationMessage, recordId);


            const channelId = new firebase.notifications.Android.Channel(
                'Default',
                'Default',
                firebase.notifications.Android.Importance.High
            );
            firebase.notifications().android.createChannel(channelId);

            let notification_to_be_displayed = new firebase.notifications.Notification({
                data: notification._android._notification._data,
                sound: 'default',
                show_in_foreground: true,
                title: notification.title,
                body: notification.body,
            });

            if (Platform.OS == 'android') {
                notification_to_be_displayed.android
                    .setPriority(firebase.notifications.Android.Priority.High)
                    .android.setChannelId('Default')
                    .android.setVibrate(1000);
            }
            console.log('FOREGROUND NOTIFICATION LISTENER: \n', notification_to_be_displayed);

            firebase.notifications().displayNotification(notification_to_be_displayed);
        });


3 commentaires

J'ai une question, je développe deux applications d'abord de l'application utilisateur et ensuite des fournisseurs, dans l'application utilisateur, j'ai créé une fonction pour envoyer une commande et l'enregistrer dans la base de données en temps réel firebase t et dans la deuxième application, je viens de récupérer le données de DB avec un auditeur pour obtenir la nouvelle commande en temps réel sans actualiser l'application, donc je veux quand j'envoie une commande de l'application utilisateur à Firebase Je veux afficher une notification dans la deuxième application? Comment gérer ces


Utilisez-vous Firebase comme base de données principale? si oui, vous devez créer une fonction dans votre première application qui enverra un déclencheur à Firebase pour générer une notification dans votre deuxième application. Si vous utilisez une base de données traditionnelle (par exemple: laravel, etc.), vous devez créer une fonction dans votre base de données qui enverra une notification à la deuxième application.


pouvez-vous vérifier ici pour plus de détails, stackoverflow.com/questions/56140314/...