首页 > 解决方案 > React-native-firebase 后台通知(Android)

问题描述

我正在使用 react-native-firebase 库,并且正在集思广益以在后台自定义通知时,我尝试遵循文档但无济于事,是否有本机代码 .java 来处理通知?

标签: androidreact-nativereact-native-firebase

解决方案


要自定义后台通知,您可以在应用程序的索引中添加:

import { AppRegistry } from 'react-native'
import App from './App'
import { backgroundMessageNotificationHandler } from 'src/common/notifications'

AppRegistry.registerComponent('testApp', () => App)
AppRegistry.registerHeadlessTask(
  'RNFirebaseBackgroundMessage',
  () => backgroundMessageNotificationHandler)

backgroundMessageNotificationHandler 可能是这样的:

export const backgroundMessageNotificationHandler = async (message: any) => {
  const localNotification = new firebase.notifications.Notification().android
    .setChannelId(androidNotificationsChannel.channelId)
    .android.setSmallIcon('iconBlackAndWhite')
    .android.setLargeIcon('iconBlackAndWhite')
    .android.setPriority(firebase.notifications.Android.Priority.High)
    .setNotificationId(message.messageId)
    .setSound('default')
    .setTitle(message.data.title)
    .setBody(message.data.body)
    .setData(message.data)

  if (Platform.OS === 'android') {
    createChannel()
  }

  firebase.notifications().displayNotification(localNotification)

  return Promise.resolve()
}

请记住按照步骤设置 build.grade、MainActivity 和 AndroidManifest。您可以按照以下帖子中指定的步骤进行操作:

通过 Firebase 的 React-Native Android 推送通知


推荐阅读