react-native-push-notification 自定义声音问题

问题描述 投票:0回答:1

我的通知代码在这里。

import React, { useState, useEffect } from 'react';
import {
    StyleSheet,
    Pressable,
    Alert,
    Text,
} from 'react-native';
import DateTimePicker from 'react-native-modal-datetime-picker';
import { connect } from 'react-redux';
import { addAlarm } from "../Actions/alarms";
import PushNotification, {Importance} from 'react-native-push-notification';

const TimePicker = (props) => {
    const [isDateTimePickerVisible, setIsDateTimePickerVisible] = useState(false);
    const [id, setId] = useState(0);
    
    useEffect(() => {
        createChannels();
        handleNotificationAction();
    }, []);

    const generateId = () => {
        const newId = id + 1;
        setId(newId);
        return newId;
    };

    const createChannels = () => {
        PushNotification.createChannel({
            channelId: "alarm-channel",
            channelName: "Alarm Channel",
        });
    };

    const handleNotificationAction = () => {
        PushNotification.configure({
            onNotification: function (notification) {
                console.log("NOTIFICATION:", notification);
            },
            popInitialNotification: true,
            requestPermissions: true,
        });
        
    };

    const showDateTimePicker = () => {
        setIsDateTimePickerVisible(true);
    };
    const hideDateTimePicker = () => {
        setIsDateTimePickerVisible(false);
    };

    const handleDatePicker = (dateTime) => {
        var currentTime = Date.now();
        if (dateTime.getTime() < currentTime) {
            Alert.alert("Please choose future time");
            hideDateTimePicker();
            return;
        }
        const fireDate = dateTime;

        const alarmNotifData = {
            channelId: "alarm-channel",
            ticker: "My Notification Message",
            importance: Importance.HIGH,
            id: generateId(),
            title: "Alarm Ringing",
            message: "Message Here",
            autoCancel: false,  // Bildirim otomatik kapanmayacak
            vibrate: true,
            vibration: 100,
            smallIcon: "ic_launcher",
            largeIcon: "ic_launcher",
            playSound: true,
            soundName: "alarm_tone",  // Sürekli çalacak alarm sesi
            color: 'red',
            tag: "some_tag",
            fire_date: fireDate,
            date: { value: dateTime },
        };
        
        props.add(alarmNotifData);
        console.log('ID: ' + alarmNotifData.id);
        
        PushNotification.localNotificationSchedule({
            channelId: "alarm-channel",
            title: alarmNotifData.title,
            id: alarmNotifData.id,
            message: "Breastfeeding Time!",
            date: alarmNotifData.fire_date,
            actions: ["Snooze", "Stop Alarm"], // Stop Alarm eklendi
            importance: Importance.HIGH,
            allowWhileIdle: true,
            invokeApp: true,
            playSound: !!alarmNotifData.soundName,                        //<-----
            soundName: alarmNotifData.soundName ? alarmNotifData.soundName : 'default',  //<-----
        });

        hideDateTimePicker();
    };

    return (
        <>
            <Pressable
                style={styles.buttonStyle}
                onPress={() => {
                    showDateTimePicker(),
                    console.log("ShowDateTime");
                }}>
                <Text style={styles.buttonText}>+ Add Alarm</Text>
            </Pressable>
            <DateTimePicker
                mode='datetime'
                isVisible={isDateTimePickerVisible}
                onConfirm={handleDatePicker}
                onCancel={hideDateTimePicker}
            />
        </>
    );
};

const styles = StyleSheet.create({
    buttonStyle: {
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: 'blue',
        paddingHorizontal: 10,
        paddingVertical: 10,
    },
    buttonText: {
        fontSize: 15,
        color: 'white',
    }
});

const mapStateToProps = state => {
    return {};
};
const mapDispatchToProps = dispatch => {
    return {
        add: alarmNotifData => {
            dispatch(addAlarm(alarmNotifData));
        }
    };
};

export default connect(mapStateToProps, mapDispatchToProps)(TimePicker);

我创建了一个通知并设置了自己的自定义声音(我还将其添加到原始文件中),但它仍然播放标准声音。

我在AndroidManifest中设置的。

<meta-data android:name="com.dieam.reactnativepushnotification.notification_sound"
    android:resource="@raw/alarm_tone" />

React Native 版本:[v0.75.3]

我的依赖:

  "dependencies": {
    "@react-native-async-storage/async-storage": "^1.24.0",
    "@react-native-community/datetimepicker": "^8.2.0",
    "@react-native-firebase/app": "^20.5.0",
    "@react-native-firebase/auth": "^20.5.0",
    "@react-native-firebase/firestore": "^20.5.0",
    "@react-native-firebase/messaging": "^20.5.0",
    "i": "^0.3.7",
    "moment": "^2.30.1",
    "npm": "^10.8.3",
    "paths-js": "^0.4.11",
    "react": "^18.2.0",
    "react-native": "0.74.3",
    "react-native-background-timer": "^2.4.1",
    "react-native-chart-kit": "^6.12.0",
    "react-native-elements": "^3.4.3",
    "react-native-gesture-handler": "^2.17.1",
    "react-native-iap": "^12.15.3",
    "react-native-modal-datetime-picker": "^18.0.0",
    "react-native-paper": "^5.12.3",
    "react-native-permissions": "^4.1.5",
    "react-native-push-notification": "^8.1.1",
    "react-native-safe-area-context": "^4.10.8",
    "react-native-svg": "^15.5.0",
    "react-redux": "^9.1.2",
    "redux": "^5.0.1"
  },

默认电话铃声仍然响起。我尝试重新启动应用程序但不起作用。我该如何解决这个问题?

react-native react-native-push-notification
1个回答
0
投票

根据“自定义声音”部分中的文档,它应该与您在资源中留下的名称相同,但在本部分中,它通过示例指定您将扩展名保留在哪里。您可以尝试保留扩展名,例如:

soundName: ‘my_sound.mp3’.

此属性可以在以下位置指定:

PushNotification.localNotification({})
PushNotification.createChannel({})

示例:

import PushNotification, {Importance} from 'react-native-push-notification';
...
  PushNotification.createChannel(
    {
      channelId: "channel-id", // (required)
      channelName: "My channel", // (required)
      channelDescription: "A channel to categorise your notifications", // (optional) default: undefined.
      playSound: false, // (optional) default: true
      soundName: "alarm_tone.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.
  );

PushNotification.localNotification({
    ...
    soundName: "alarm_tone.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)
    ...
});

根据文档中的观察,没有 com.dieam.reactnativepushnotification.notification_sound 的资源,因此 Android 清单中的行是不必要的。

https://www.npmjs.com/package/react-native-push-notification#custom-sounds https://www.npmjs.com/package/react-native-push-notification#channel-management-android

© www.soinside.com 2019 - 2024. All rights reserved.