Notifee自定义声音在前台工作,而不是在React Native的后台工作

dzjeubhm  于 2023-01-31  发布在  React
关注(0)|答案(1)|浏览(177)

我正在尝试使用React Native构建一个应用程序,我需要在其中发送带有一些自定义通知声音的通知。Notifee在前台显示通知和声音,但在后台不播放声音。这是我的App.js

import React, {useEffect} from 'react';
import messaging from '@react-native-firebase/messaging';
import {
  SafeAreaView,
  Button,

} from 'react-native';
import notifee from '@notifee/react-native';
import {
  getFCMToken,
  requestUserPermission,
} from './src/NotificationHandler';
import {onDisplayNotification} from './src/BackgroundNotification';

const App = () => {
  useEffect(() => {
    requestUserPermission();
    getFCMToken();
  }, []);

  useEffect(() => {
    const unsubscribe = messaging().onMessage(async remoteMessage => {
      onDisplayNotification();
    });

    return unsubscribe;
  }, []);
  return (
    <SafeAreaView>
      <Button title="Display Notification" onPress={onDisplayNotification} />
    </SafeAreaView>
  );
};

export default App;

我还在Index.js中注册了Firebase后台服务,如下所示

import {AppRegistry} from 'react-native';
import messaging from '@react-native-firebase/messaging';
import App from './App';
import {name as appName} from './app.json';
import {onDisplayNotification} from './src/BackgroundNotification';
import notifee, {EventType} from '@notifee/react-native';

messaging().setBackgroundMessageHandler(async remoteMessage => {
  console.log('Message handled in the background!', remoteMessage);
  onDisplayNotification();
});

AppRegistry.registerComponent(appName, () => App);

onDisplayNotification是负责处理Notifee通知的函数,如下所示

import notifee from '@notifee/react-native';

export async function onDisplayNotification() {
  console.log('ondisplaynotification');
  // Request permissions (required for iOS)
  await notifee.requestPermission();

  // Create a channel (required for Android)
  const channelId = await notifee.createChannel({
    id: 'default',
    name: 'Default Channel',
    sound: 'customsound',
    vibration: true,
    vibrationPattern: [300, 500],
  });
  console.log('sound playing');
  // Display a notification
  await notifee.displayNotification({
    title: 'Notification Title',
    body: 'Main body content of the notification',
    android: {
      sound: 'customsound',
      vibration: true,
      vibrationPattern: [300, 500],

      channelId,
      //   smallIcon: 'name-of-a-small-icon', // optional, defaults to 'ic_launcher'.
      // pressAction is needed if you want the notification to open the app when pressed
      pressAction: {
        id: 'default',
      },
    },
  });
}

有趣的是,我正在让日志正常工作。我可以在日志Sound Playing中看到这一点,但声音并不总是播放。有时它在后台播放声音,有时它不播放声音,但通知出现了。有没有办法在后台一直播放自定义通知声音,即使在设备锁定或屏幕关闭时?

cfh9epnr

cfh9epnr1#

对于我的问题,我在这里启用了Firebase。

相关问题