简体   繁体   English

推送通知未显示在 Android 前台

[英]Push notification not showing in Android foreground

I've used react-native-fcm for remote notification in android and iPhone.我在 android 和 iPhone 中使用react-native-fcm进行远程通知。

react-native-fcm react-native-fcm

In Android foreground I'm not be able to getting remote notification in notification bar.在 Android 前台,我无法在通知栏中收到远程通知。

In background mode I'm able to getting notification successfully but some how in foreground doesn't.在后台模式下,我能够成功收到通知,但在前台却没有。

Android Manifest.xml Android Manifest.xml

<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>

App.js应用程序.js

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
    });
  };

I'm suffering this issue from last 2 months and not get it well solution for the same as i doing so many new attempt to resolve issue but at the end not getting any succeed.我从过去 2 个月开始就遇到了这个问题,并且没有得到很好的解决方案,因为我做了很多新的尝试来解决问题,但最终没有取得任何成功。

According to the official Github of react-native-fcm , this library is depreciated.根据react-native-fcm的官方 Github ,该库已折旧。 You can use the react-native-firebase for generating notification.您可以使用react-native-firebase来生成通知。 I was able to get the notifications working in about 2 hours for android.我能够在大约 2 小时内为 android 发送通知。 If you want the code I can share it.如果你想要代码,我可以分享它。 good luck.祝你好运。

Update - Sorry I couldn't answer earlier because of my office account.更新 - 抱歉,由于我的办公室帐户,我无法更早地回答。

This is my code for showing android foreground notifications.这是我用于显示 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);
        });

As per the library issues listed here you can try two things:根据此处列出的库问题您可以尝试两件事:

  1. just pass show_in_foreground in your data property in remote notification只需在远程通知的data属性中传递show_in_foreground

  2. android shows notification only when app state is killed or background. android 仅在应用程序状态被终止或后台时才显示通知。 To display notifications in app foreground, you need to show local notification .要在应用程序前台显示通知,您需要显示local notification

Sample 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)
    });
  }

Full code is here完整代码在这里

Which API level you are testing on ?您正在测试哪个 API 级别? Android API 26 and above requires channels to be created in order to receive notifications in foreground. Android API 26 及更高版本需要创建通道才能在前台接收通知。 please read this for more information.请阅读本文以获取更多信息。

react-native-fcm is also updated to include channels too, refer this though the library should not be used anymore as the library is not maintained anymore, a good alternative is react-native-firebase . react-native-fcm也更新为包含通道,尽管不应再使用该库,因为该库不再维护,请参考,一个很好的替代方案是react-native-firebase

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM