You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native Push Notification自定义声音不生效问题求助

问题描述

在React Native项目中使用react-native-push-notification设置自定义通知声音,已将音频文件放入raw目录,也在AndroidManifest.xml中配置了相关meta-data,但通知仍播放系统默认声音,重启应用后问题依旧。

相关代码

通知组件代码

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" />

依赖配置

"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版本:v0.75.3


解决方案

1. 修复通知通道的声音配置

Android 8.0+ 通知声音绑定到通知通道,你创建通道时未指定声音,导致通道使用系统默认配置,后续通知的声音设置会被通道覆盖。修改createChannels方法:

const createChannels = () => {
    PushNotification.createChannel({
        channelId: "alarm-channel",
        channelName: "Alarm Channel",
        soundName: "alarm_tone", // 新增此行,指定通道的自定义声音
        importance: Importance.HIGH,
        vibration: true,
    });
};

2. 清除已存在的旧通道

Android通道创建后无法直接修改,之前创建的无声音通道会保留,需先清除:

  • 直接卸载应用重新安装
  • 或在手机设置的「应用通知」中找到你的应用,删除Alarm Channel通道后重启应用

3. 检查音频文件格式和命名

  • 确保音频文件为Android支持的格式(如MP3、WAV),文件名全小写,无特殊字符和空格
  • 确认文件确实放在android/app/src/main/res/raw/目录下,文件名拼写无误

4. 简化通知声音配置

在localNotificationSchedule中直接指定声音参数,避免逻辑判断可能带来的问题:

playSound: true,
soundName: "alarm_tone",

5. 确认权限状态

确保应用已获取通知权限,可在启动时主动请求:

PushNotification.requestPermissions();

内容的提问来源于stack exchange,提问作者skywalker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 03:47:05