猿问

应用处于后台时发送的发送鸟推送通知

这是我的查询。我已经在我的一个react-native应用程序中实现了sendbird sdk,用于聊天实现。我正在尝试实现推送通知。我已经使用react-native-firebase作为firebase推送通知,如sendbird的文档中描述的那样。现在的问题是,当应用程序处于前台时,我的Android应用程序会收到推送通知。为此触发 OnMessageReceived() 侦听器。但是,当我的应用程序处于后台时,我不会收到来自 sendbird 的任何推送通知。不会触发任何 firebase 通知侦听器。


此外,当我尝试从firebase控制台发送通知时,我会收到前台和后台通知。


希望得到你们的回应,因为这可以帮助我成功实现此功能。


我的通知侦听器代码与此类似。但是,这里没有添加显示通知代码。


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

  );

}

}


慕村9548890
浏览 145回答 2
2回答

梵蒂冈之花

因此,经过大量研究,我终于通过参考Sendbird的示例应用程序,粘贴下面的链接,成功地得到了解决方案。https://github.com/sendbird/SendBird-JavaScript/tree/master/react-native-redux-sample解决方案:-您需要在 App. Js componentDidMount() 中注册通道。应用程序 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 changeAppstate.addEventListener('change',this._handleAppStateChange);)}_handleAppStateChange = currentAppState =>{  const sb = SendBird.getInstance();if(sb){   if(currentAppState == "active")  {     sb.setForegroundState();  }else if(currentAppState == "background"){   sb.setBackgroundState();}}现在在主索引中.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.导入的推送/背景Push是一个包含以下源代码的文件:-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();  }};这是适用于我的查询Android后台推送通知的解决方案,未收到。虽然,仍然在努力接收推送通知iOS方面。

茅侃侃

对于安卓设置为通知有效负载"priority": "high"{&nbsp; "to": "cjUyGxLa3pU...",&nbsp; "data": {&nbsp; &nbsp; "title": "Some title",&nbsp; &nbsp; "body": "Some text"&nbsp; },&nbsp; "priority": "high"}对于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) {&nbsp; &nbsp; [FIRApp configure];&nbsp; }if ([UNUserNotificationCenter class] != nil) {&nbsp; &nbsp; // iOS 10 or later&nbsp; &nbsp; // For iOS 10 display notification (sent via APNS)&nbsp; &nbsp; [UNUserNotificationCenter currentNotificationCenter].delegate = self;&nbsp; &nbsp; UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert |&nbsp; &nbsp; UNAuthorizationOptionSound | UNAuthorizationOptionBadge;&nbsp; &nbsp; [[UNUserNotificationCenter currentNotificationCenter]&nbsp; &nbsp; requestAuthorizationWithOptions:authOptions&nbsp; &nbsp; completionHandler:^(BOOL granted, NSError * _Nullable error) {&nbsp; &nbsp; // …&nbsp; &nbsp; }];&nbsp; &nbsp;} else {&nbsp; &nbsp; // iOS 10 notifications aren’t available; fall back to iOS 8–9 notifications.&nbsp; &nbsp; UIUserNotificationType allNotificationTypes =&nbsp; &nbsp; (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);&nbsp; &nbsp; UIUserNotificationSettings *settings =&nbsp; &nbsp; [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];&nbsp; &nbsp; [application registerUserNotificationSettings:settings];&nbsp; &nbsp;}&nbsp; [application registerForRemoteNotifications];&nbsp; [FIRMessaging messaging].delegate = self;&nbsp; [[FIRInstanceID instanceID] instanceIDWithHandler:^(FIRInstanceIDResult * _Nullable result,&nbsp; &nbsp; NSError * _Nullable error) {&nbsp; &nbsp; &nbsp; if (error != nil) {&nbsp; &nbsp; &nbsp; &nbsp; NSLog(@"Error fetching remote instance ID: %@", error);&nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; NSLog(@"Remote instance ID token: %@", result.token);&nbsp; &nbsp; &nbsp; &nbsp; NSString* message = [NSString stringWithFormat:@"Remote InstanceID token: %@", result.token];&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; ];&nbsp; [FIRMessaging messaging].autoInitEnabled = YES;...}- (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken {&nbsp; NSLog(@"FCM registration token: %@", fcmToken);&nbsp; NSDictionary *dataDict = [NSDictionary dictionaryWithObject:fcmToken forKey:@"token"];&nbsp; [[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{&nbsp; completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge);}如果你在info.plist上没有这个密钥,那么你也可以添加在更改AppDelegate.m之前先尝试FirebaseAppDelegateProxyEnabled: YESInfo.plist注意:1.5年前,我使用了相同的react-native-firebase库,我收到了同样的问题,因为后来我搬到了react-native-fcm库,因为该库维护得很好
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答