简体   繁体   English

当应用程序处于后台时发送鸟推送通知

[英]Sendbird push notification when app is in background

Here is my query.这是我的查询。 I have implemented sendbird sdk in one of my react-native app for chat implementation.我已经在我的 react-native 应用程序之一中实现了 sendbird sdk 来实现聊天。 I am trying to implement push notifications.我正在尝试实施推送通知。 I have used react-native-firebase for firebase push notifications as described in sendbird's documentation.如 sendbird 的文档中所述,我已将 react-native-firebase 用于 firebase 推送通知。 Now the issue is my android app is getting push notification when the app is in foreground.现在的问题是我的 android 应用程序在前台时收到推送通知。 OnMessageReceived() listener is triggered for this.为此触发 OnMessageReceived() 侦听器。 But when my app is in background I am not receiving any push notification from sendbird.. None of the firebase notification listeners are triggered.但是当我的应用程序在后台时,我没有收到来自 sendbird 的任何推送通知。firebase 通知监听器都没有被触发。

Also, when I am trying to send notification from firebase console I am receiving foreground as well as background notification.此外,当我尝试从 firebase 控制台发送通知时,我收到了前台和后台通知。

Hoping for a response from you guys, as this can help me implement this feature successfully.希望得到你们的回应,因为这可以帮助我成功实现这个功能。

My notification listener code is similar to this.我的通知侦听器代码与此类似。 But, here haven't added display notification code though.但是,这里并没有添加显示通知代码。

async componentDidMount() {
  this.checkPermission();
  this.createNotificationListeners(); //Notification listener 
}

 async createNotificationListeners() {
  /*
  * Triggered when a particular notification has been received in foreground
  * */
  this.notificationListener = firebase.notifications().onNotification((notification) => {
      const { title, body } = notification;
      this.showAlert(title, body);
  });

  /*
  * 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;
      this.showAlert(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;
      this.showAlert(title, body);
  }
  /*
  * Triggered for data only payload in foreground
  * */
  this.messageListener = firebase.messaging().onMessage((message) => {
    //process data message
    console.log(JSON.stringify(message));
  });
}

showAlert(title, body) {
  Alert.alert(
    title, body,
    [
        { text: 'OK', onPress: () => console.log('OK Pressed') },
    ],
    { cancelable: false },
  );
}
}

My AndroidManifest.xml code is as below:-我的 AndroidManifest.xml 代码如下:-

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WAE_LOCK"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

<application ....

<activity android:name="com.facebook.devsupport.DevSettingsActivity"/>
<service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService" android:exported="false">

<intent-filter>
   <action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService"/>

<meta-data androd:name="com.google.firebase.messaging.default_notification_icon"
androd:resource="@mipmap/ic_launcher_logo"/>

<meta-data androd:name="com.google.firebase.messaging.default_notification_channel_id"
androd:value="test-channel"/>

</application>

So finally after lot of research, I successfully got the solution by refering to the Sendbird's sample App, pasting link below.所以最后经过大量研究,我参考了Sendbird的示例应用程序,成功地得到了解决方案,粘贴下面的链接。

https://github.com/sendbird/SendBird-JavaScript/tree/master/react-native-redux-sample https://github.com/sendbird/SendBird-JavaScript/tree/master/react-native-redux-sample

Solution:-解决方案:-

You need to register channel in App.您需要在 App 中注册频道。 Js componentDidMount(). Js componentDidMount()。

//code for app js //应用程序js代码

componentDidMount(){
const channel = new firebase.notification.Android.Channel(
"YOUR-CHANNEL-ID",
"CHANNEL NAME",
firebase.notification.Android.Importance.Max).setDescription("description);
firebase.notifications().android.createChannel(chanel);


//don't forget to add handler for app state change
Appstate.addEventListener('change',this._handleAppStateChange);

)
}

_handleAppStateChange = currentAppState =>{
  const sb = SendBird.getInstance();
if(sb)
{
   if(currentAppState == "active")
  {
     sb.setForegroundState();
  }
else if(currentAppState == "background")
{
   sb.setBackgroundState();
}
}

//NOW in main index.js add below lines //现在在主 index.js 中添加以下行

import backgroundPush from './Services/push';

AppRegistry.registerHeadlessTask('RNFirebaseBackgroundMessage',()=>backgroundPush) //add this line after appRegistry Component and this is a key to be added to get notitification in background when using sendbird, whicch is nowhere mentioned in its official doc. It is in the sample App I have also added link to it.

And the push/backgroundPush that imported is a file containing below source:-导入的 push/backgroundPush 是一个包含以下源的文件:-

push.js //this file is in sample app though push.js //这个文件在示例应用程序中

import firebase from 'react-native-firebase'

export default async message => {
  try {
    const text = message.data.message;
    const payload = JSON.parse(message.data.sendbird);
    const localNotification = new firebase.notifications.Notification({
      show_in_foreground: true
    }).android
      .setChannelId('channel_id')
      .android.setSmallIcon('sendbird_ic_notification')
      .android.setPriority(firebase.notifications.Android.Priority.High)
      .setNotificationId(message.messageId)
      .setTitle('New message')
      .setSubtitle(`Unread message: ${payload.unread_message_count}`)
      .setBody(text)
      .setData(payload);
    return firebase.notifications().displayNotification(localNotification);
  } catch (e) {
    return Promise.resolve();
  }
};

This is the solution worked for me for my query Android background push notification not received.这是适用于我的查询 Android 未收到后台推送通知的解决方案。 Although, still struggling with receiving push notificaiton iOS side.虽然,仍在努力接收推送通知 iOS 端。

Thanks.谢谢。

For android set "priority": "high" into notification payload对于 android,将"priority": "high"设置为通知负载

{
  "to": "cjUyGxLa3pU...",
  "data": {
    "title": "Some title",
    "body": "Some text"
  },
  "priority": "high"
}

for ios i think it will able to get background and foreground notifications working by using the following code in my AppDelegate.m :对于 ios,我认为它可以通过在我的AppDelegate.m中使用以下代码来获得后台和前台通知:

#import <UserNotifications/UserNotifications.h>
#import <Firebase.h>
#import <FirebaseInstanceID/FirebaseInstanceID.h>
#import <FirebaseMessaging.h>

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if ([FIRApp defaultApp] == nil) {
    [FIRApp configure];
  }

if ([UNUserNotificationCenter class] != nil) {
    // iOS 10 or later
    // For iOS 10 display notification (sent via APNS)
    [UNUserNotificationCenter currentNotificationCenter].delegate = self;
    UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert |
    UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
    [[UNUserNotificationCenter currentNotificationCenter]
    requestAuthorizationWithOptions:authOptions
    completionHandler:^(BOOL granted, NSError * _Nullable error) {
    // …
    }];
   } else {
    // iOS 10 notifications aren’t available; fall back to iOS 8–9 notifications.
    UIUserNotificationType allNotificationTypes =
    (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
    UIUserNotificationSettings *settings =
    [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
    [application registerUserNotificationSettings:settings];
   }
  [application registerForRemoteNotifications];
  [FIRMessaging messaging].delegate = self;
  [[FIRInstanceID instanceID] instanceIDWithHandler:^(FIRInstanceIDResult * _Nullable result,
    NSError * _Nullable error) {
      if (error != nil) {
        NSLog(@"Error fetching remote instance ID: %@", error);
      } else {
        NSLog(@"Remote instance ID token: %@", result.token);
        NSString* message = [NSString stringWithFormat:@"Remote InstanceID token: %@", result.token];
      }
    }
  ];
  [FIRMessaging messaging].autoInitEnabled = YES;

...
}

- (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken {
  NSLog(@"FCM registration token: %@", fcmToken);
  NSDictionary *dataDict = [NSDictionary dictionaryWithObject:fcmToken forKey:@"token"];
  [[NSNotificationCenter defaultCenter] postNotificationName: @"FCMToken" object:nil userInfo:dataDict];
}

/Called when a notification is delivered to a foreground app.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
  completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge);
}

also removed FirebaseAppDelegateProxyEnabled: YES in Info.plist if you have not this key on info.plist then you can add to try first before changing AppDelegate.m还删除了FirebaseAppDelegateProxyEnabled: YES in Info.plist如果你在 info.plist 上没有这个键,那么你可以在更改 AppDelegate.m 之前先添加尝试

Note: 1.5 years ago I used the same react-native-firebase library I received the same issue because then I moved to react-native-fcm library because that library is highly maintained注意: 1.5 年前,我使用了相同的 react-native-firebase 库,我收到了同样的问题,因为后来我搬到了react-native-fcm库,因为该库得到了高度维护

暂无
暂无

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

相关问题 当应用程序在后台并单击通知时,Android react-native-push-notification onNotification 没有被调用? - Android react-native-push-notification onNotification not called when app is in the background and notification clicked? 应用程序被终止时,设备未收到推送通知 - push notification not received to devices when app is killed Firebase app在后台时如何处理通知 - How to handle notification when app in background in Firebase Flutter Firebase 消息 - 应用打开时不显示推送通知 - Flutter Firebase messaging - push notification is not showing when app is open 第一次安装应用程序时未收到推送通知 - Push notification is not receiving when the app is installed for first time FCM iOS 推送通知在应用程序终止时捕获自定义数据? - FCM iOS push notification capture custom data when app is terminated? 点击通知时无法导航到特定页面(当应用程序处于后台时) - Cannot navigate to a specific page when tapping a notification (when app is in background) 通过 api 显示应用程序在后台时收到的 Firebase 消息通知 - Show Notification of Firebase Message onReceived when App is in Background Through api Firebase 推送通知在后台应用程序时显示错误图标 - Firebase push notifications show wrong icon when app in background Flutter:当应用程序处于后台时无法显示本地通知 - Flutter: Not able to show local notification when the app is in background
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM