首页 > 解决方案 > 使用 react-native-fcm 正确设置

问题描述

我觉得react-native-fcm的文档有点乱,我很难弄清楚这一点。

我目前有一个生产应用程序,我的 android 用户告诉我他们没有收到他们应该收到的事件通知。所以这让我现在压力很大。在 iOS 上一切似乎都很好。

react-native-fcm 示例应用程序中,您可以看到以下内容:

//FCM.createNotificationChannel is mandatory for Android targeting >=8. Otherwise you won't see any notification

componentDidMount() {
  FCM.createNotificationChannel({
    id: 'default',
    name: 'Default',
    description: 'used for example',
    priority: 'high'
  })
}

需要打电话FCM.createNotificationChannel()吗??我主要使用远程通知,所以这有什么关系吗?

这是我的设置:

import FCM, {
  FCMEvent,
  NotificationType,
  RemoteNotificationResult,
  WillPresentNotificationResult,
} from 'react-native-fcm';

FCM.on(FCMEvent.Notification, async (notif) => {

  // there are two parts of notif. notif.notification contains the notification payload, notif.data contains data payload
  FCM.presentLocalNotification({
    id: "new_message",                               // (optional for instant notification)
    title: notif.fcm.title,                          // as FCM payload
    body: notif.fcm.body,                               // as FCM payload (required)
    sound: "default",                                   // as FCM payload
    priority: "high",                                   // as FCM payload
    click_action: "com.myapp.MyCategory",               // as FCM payload - this is used as category identifier on iOS.
    badge: 10,                                          // as FCM payload IOS only, set 0 to clear badges
    number: 10,                                         // Android only
    ticker: "My Notification Ticker",                   // Android only
    auto_cancel: true,                                  // Android only (default true)
    large_icon: "ic_launcher",                           // Android only
    icon: "ic_launcher",                                // as FCM payload, you can relace this with custom icon you put in mipmap
    color: "blue",                                      // Android only
    vibrate: 300,                                       // Android only default: 300, no vibration if you pass 0
    wake_screen: true,                                  // Android only, wake up screen when notification arrives
    group: "group",                                     // Android only
    picture: "https://google.png",                      // Android only bigPicture style
    ongoing: false,                                      // Android only
    my_custom_data:'my_custom_field_value',             // extra data you want to throw
    lights: true,                                       // Android only, LED blinking (default false)
  });

  if(Platform.OS ==='ios'){
    //optional
    //iOS requires developers to call completionHandler to end notification process. If you do not call it your background remote notifications could be throttled, to read more about it see https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623013-application.
    //This library handles it for you automatically with default behavior (for remote notification, finish with NoData; for WillPresent, finish depend on "show_in_foreground"). However if you want to return different result, follow the following code to override
    //notif._notificationType is available for iOS platfrom
    switch(notif._notificationType){
      case NotificationType.Remote:
        notif.finish(RemoteNotificationResult.NewData) //other types available: RemoteNotificationResult.NewData, RemoteNotificationResult.ResultFailed
        break;
      case NotificationType.NotificationResponse:
        notif.finish();
        break;
      case NotificationType.WillPresent:
        notif.finish(WillPresentNotificationResult.All) //other types available: WillPresentNotificationResult.None
        break;
    }
  }
});

FCM.on(FCMEvent.RefreshToken, (token) => {
    try {
      const { currentUser } = firebase.auth();

      let updates = {};
      updates[`/allUsers/serviceUsers/${currentUser.uid}/userInfo/fcmToken`] = token;

      return firebase.database().ref().update(updates).catch(err => console.log('fcm refresh error', err))
    } catch (e) {
      console.log('couldnt update fcm refresh token', e)
    }
});

const store = createStore(reducers, {}, applyMiddleware(ReduxThunk));

class App extends Component {
  componentWillMount() {

    let config = {configgg}

    !firebase.apps.length ? firebase.initializeApp(config) : firebase.app();

    FCM.requestPermissions();
  }

  render() {
    return (
      <Provider store={store}>
        <Router/>
      </Provider>
    );
  }
}

export default App;

我主要使用远程通知,这对我的应用程序的工作至关重要。我的设置中有什么遗漏吗?

任何提示或建议都会对我有很大帮助!谢谢!

编辑:

收到通知时在 adb logcat 中发现了这个(未显示)

NotificationService: No Channel found for pkg=com.lisdoworker, channelId=null, id=0, tag=GCM-Notification:9015992, opPkg=com.lisdoworker, callingUid=10487, userId=0, incomingUserId=0, notificationUid=10487, notification=Notification(channel=null pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x10 color=0x00000000 vis=PRIVATE)

这有关系FCM.createNotificationChannel()吗??

标签: react-nativereact-native-fcm

解决方案


是的,显然createNotificationChannel是在版本 16 中添加以支持 Android 8 并且几乎没有记录。


推荐阅读