【问题标题】:Create notification channel react native创建通知通道反应原生
【发布时间】:2021-02-09 00:59:21
【问题描述】:

我正在使用 react-native-firebase v6 来处理推送通知。 由于这个版本没有没有创建channel id功能,那么在react native项目中创建channel id的解决方案是什么?

【问题讨论】:

    标签: android react-native push-notification


    【解决方案1】:

    你可以使用这个库https://github.com/zo0r/react-native-push-notification 然后

          PushNotification.createChannel(
        {
          channelId: "channel-id", // (required)
          channelName: "My channel", // (required)
          channelDescription: "A channel to categorise your notifications", // (optional) default: undefined.
          soundName: "default", // (optional) See `soundName` parameter of `localNotification` function
          importance: 4, // (optional) default: 4. Int value of the Android notification importance
          vibrate: true, // (optional) default: true. Creates the default vibration patten if true.
        },
        (created) => console.log(`createChannel returned '${created}'`) // (optional) callback returns whether the channel was created, false means it already existed.
      );
    

    【讨论】:

      【解决方案2】:

      基本上频道只创建一次,直到您卸载并重新安装应用程序。

      所以在主文件中添加 createChannel [即 index.js/App.js]。 e 创建频道请参考以下代码

      PushNotification.createChannel(
          {
            channelId: 'channel-id', // (required)
            channelName: 'My channel', // (required)
            channelDescription: 'A channel to categorise your notifications', // (optional) default: undefined.
            playSound: true, // (optional) default: true
            soundName: 'notification.mp3', // (optional) See `soundName` parameter of `localNotification` function
            importance: Importance.HIGH, // (optional) default: Importance.HIGH. Int value of the Android notification importance
            vibrate: true, // (optional) default: true. Creates the default vibration pattern if true.
          },
          (created) => console.log(`createChannel returned '${created}'`), // (optional) callback returns whether the channel was created, false means it already existed.
        );
      

      一旦频道创建完成,然后创建文件来处理 pushNotifications 和下面的代码

      export const showLocalNotification = ({title, body, id, number}, messageId) =>
        PushNotification.localNotification({
          channelId: 'channel-id', // (required) channelId, if the channel doesn't exist, notification will not trigger.
          ticker: 'Hey', // (optional)
          showWhen: true, // (optional) default: true
          autoCancel: true, // (optional) default: true
          largeIcon: 'ic_launcher', // (optional) default: "ic_launcher". Use "" for no large icon.
          // largeIconUrl: 'https://www.example.tld/picture.jpg', // (optional) default: undefined
          smallIcon: 'ic_notification', // (optional) default: "ic_notification" with fallback for "ic_launcher". Use "" for default small icon.
          // bigText: '', // (optional) default: "message" prop
          // subText: '', // (optional) default: none
          // bigPictureUrl: 'https://www.example.tld/picture.jpg', // (optional) default: undefined
          bigLargeIcon: 'ic_launcher', // (optional) default: undefined
          // bigLargeIconUrl: 'https://www.example.tld/bigicon.jpg', // (optional) default: undefined
          // color: 'red', // (optional) default: system default
          vibrate: true, // (optional) default: true
          vibration: 300, // vibration length in milliseconds, ignored if vibrate=false, default: 1000
          tag: 'some_tag', // (optional) add tag to message
          group: 'group', // (optional) add group to message
          groupSummary: false, // (optional) set this notification to be the group summary for a group of notifications, default: false
          ongoing: false, // (optional) set whether this is an "ongoing" notification
          priority: 'high', // (optional) set notification priority, default: high
          visibility: 'private', // (optional) set notification visibility, default: private
          ignoreInForeground: false, // (optional) if true, the notification will not be visible when the app is in the foreground (useful for parity with how iOS notifications appear). should be used in combine with `com.dieam.reactnativepushnotification.notification_foreground` setting
          shortcutId: 'shortcut-id', // (optional) If this notification is duplicative of a Launcher shortcut, sets the id of the shortcut, in case the Launcher wants to hide the shortcut, default undefined
          onlyAlertOnce: true, // (optional) alert will open only once with sound and notify, default: false
      
          when: null, // (optional) Add a timestamp (Unix timestamp value in milliseconds) pertaining to the notification (usually the time the event occurred). For apps targeting Build.VERSION_CODES.N and above, this time is not shown anymore by default and must be opted into by using `showWhen`, default: null.
          usesChronometer: false, // (optional) Show the `when` field as a stopwatch. Instead of presenting `when` as a timestamp, the notification will show an automatically updating display of the minutes and seconds since when. Useful when showing an elapsed time (like an ongoing phone call), default: false.
          timeoutAfter: null, // (optional) Specifies a duration in milliseconds after which this notification should be canceled, if it is not already canceled, default: null
      
          messageId: `${number}:${id}`, // (optional) added as `message_id` to intent extras so opening push notification can find data stored by @react-native-firebase/messaging module.
      
          // actions: ['Yes', 'No'], // (Android only) See the doc for notification actions to know more
          invokeApp: true, // (optional) This enable click on actions to bring back the application to foreground or stay in background, default: true
          // repeatType: 'day', // (optional) Repeating interval. Check 'Repeating Notifications' section for more info.
          /* iOS only properties */
          category: '', // (optional) default: empty string
          // subtitle: 'My Notification Subtitle', // (optional) smaller title below notification title
      
          /* iOS and Android properties */
          id, // (optional) Valid unique 32 bit integer specified as string. default: Autogenerated Unique ID
          title: title, // (optional)
          message: body, // (required)
          // picture: 'https://www.example.tld/picture.jpg', // (optional) Display an picture with the notification, alias of `bigPictureUrl` for Android. default: undefined
          userInfo: {}, // (optional) default: {} (using null throws a JSON value '<null>' error)
          playSound: true, // (optional) default: true
          importance: Importance.HIGH,
          soundName: 'notification.mp3', // (optional) Sound to play when the notification is shown. Value of 'default' plays the default sound. It can be set to a custom sound such as 'android.resource://com.xyz/raw/my_sound'. It will look for the 'my_sound' audio file in 'res/raw' directory and play it. default: 'default' (default sound is played)
          number, // (optional) Valid 32 bit integer specified as string. default: none (Cannot be zero)
        });
      

      要在应用程序处于后台时处理消息,请在 index.android.js 中编写以下代码

      import messaging from '@react-native-firebase/messaging';
      messaging().setBackgroundMessageHandler(async (remoteMessage) => {
        showLocalNotification({title: remoteMessage.data.title, body: remoteMessage.data.body}, remoteMessage.messageId);
        return Promise.resolve();
      });
      

      在应用程序关闭/终止时处理消息在 index.android.js 中编写以下代码

      AppRegistry.registerHeadlessTask(
            'RNFirebaseBackgroundMessage',
            () => firebaseBackgroundMessage,
          );
      

      firebaseBackgroundMessage 函数如下所示,并返回一个 promise 解析器

      export async function firebaseBackgroundMessage(message) {
        showLocalNotification({title: message.data.title,body: message.data.body}, message.messageId);
        return Promise.resolve();
      }
      

      快乐编码...

      【讨论】:

        猜你喜欢
        • 2019-05-16
        • 1970-01-01
        • 2019-09-29
        • 2018-01-17
        • 2017-12-18
        • 1970-01-01
        • 2018-05-27
        • 2019-09-28
        • 1970-01-01
        相关资源
        最近更新 更多