首页 > web前端 > js教程 > 正文

为 Expo 应用添加声音和震动通知

DDD
发布: 2025-08-22 17:20:26
原创
614人浏览过

为 expo 应用添加声音和震动通知

本文档旨在指导开发者如何在 Expo 应用中集成声音和震动通知功能。通过使用 expo-av 和 react-native 提供的 Vibration API,你可以为你的应用添加更丰富的用户体验。本文将详细介绍如何配置通知处理程序、加载和播放声音文件,以及触发设备震动,并提供示例代码和注意事项,帮助你解决常见问题,成功实现声音和震动通知。

准备工作

首先,确保你的 Expo 项目已经安装了必要的依赖包。 如果没有,请使用以下命令安装:

npx expo install expo-notifications expo-av
登录后复制

此外,react-native 已经内置了 Vibration API,无需额外安装。

配置通知处理程序

要使声音和震动在通知到达时生效,你需要正确配置 Notifications.setNotificationHandler。 这个函数允许你自定义通知的处理方式。

import * as Notifications from 'expo-notifications';

Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: true,
    shouldSetBadge: false,
  }),
});
登录后复制

shouldPlaySound: true 确保通知到达时播放声音。 shouldShowAlert: true 确保显示通知横幅。

添加声音通知

使用 expo-av 播放声音文件,需要在应用中加载声音资源并在通知触发时播放。

  1. 加载声音文件: 使用 Audio.Sound.createAsync 加载声音文件。

    import { Audio } from 'expo-av';
    import { useEffect, useState } from 'react';
    
    const [sound, setSound] = useState(null);
    
    useEffect(() => {
      async function loadSound() {
        try {
          const { sound } = await Audio.Sound.createAsync(
            require('./assets/notification_sound.mp3') // 替换为你的声音文件路径
          );
          setSound(sound);
        } catch (error) {
          console.error('Failed to load sound', error);
        }
      }
    
      loadSound();
    
      return () => {
        if (sound) {
          sound.unloadAsync();
        }
      };
    }, []);
    登录后复制

    确保将 notification_sound.mp3 替换为你实际的声音文件路径。

  2. 播放声音: 在发送通知时,确保通知内容包含 sound 属性。 如果使用本地通知,则无需额外配置。 如果使用推送通知,请确保推送 payload 中包含 sound 字段。

    示例 (本地通知):

    import * as Notifications from 'expo-notifications';
    
    async function schedulePushNotification() {
      await Notifications.scheduleNotificationAsync({
        content: {
          title: "Reminder!",
          body: 'Time to do something!',
          data: { data: 'goes here' },
        },
        trigger: { seconds: 5 },
      });
    }
    登录后复制

    确保在发送通知之前,声音文件已经成功加载。

添加震动通知

使用 react-native 的 Vibration API 可以触发设备震动。

import { Vibration } from 'react-native';

const vibrate = () => {
  Vibration.vibrate(); // 默认震动 500ms
};

// 可以自定义震动模式
const vibrateCustom = () => {
  const pattern = [0, 500, 200, 500]; // 停止 0ms, 震动 500ms, 停止 200ms, 震动 500ms
  Vibration.vibrate(pattern);
};

const stopVibration = () => {
  Vibration.cancel();
};
登录后复制

在需要触发震动的地方调用 vibrate() 或 vibrateCustom() 函数。 Vibration.cancel() 可以停止正在进行的震动。

在通知处理程序中触发震动:

import * as Notifications from 'expo-notifications';
import { Vibration } from 'react-native';

Notifications.setNotificationHandler({
  handleNotification: async () => {
    Vibration.vibrate(); // 在收到通知时震动
    return {
      shouldShowAlert: true,
      shouldPlaySound: true,
      shouldSetBadge: false,
    };
  },
});
登录后复制

权限处理

确保你的应用具有发送通知的权限。 使用 Notifications.getPermissionsAsync() 检查权限状态,并使用 Notifications.requestPermissionsAsync() 请求权限。

import * as Notifications from 'expo-notifications';
import { Alert } from 'react-native';
import { useEffect } from 'react';

useEffect(() => {
  async function configurePushNotifications() {
    const { status } = await Notifications.getPermissionsAsync();
    let finalStatus = status;

    if (finalStatus !== 'granted') {
      const { status } = await Notifications.requestPermissionsAsync();
      finalStatus = status;
    }

    if (finalStatus !== 'granted') {
      Alert.alert(
        'Permission required',
        'Local notifications need the appropriate permissions.'
      );
      return;
    }

    // 权限已授予,可以执行后续操作
  }

  configurePushNotifications();
}, []);
登录后复制

注意事项

  • 声音文件格式: 确保你的声音文件格式正确,并且与 expo-av 兼容 (例如:.mp3, .wav)。
  • 文件路径: 检查声音文件的路径是否正确。 使用 require() 引入本地资源时,路径必须相对于当前文件。
  • 权限: 确保用户已授予应用发送通知的权限。
  • 声音资源释放: 在组件卸载时,使用 sound.unloadAsync() 释放声音资源,防止内存泄漏。
  • 震动模式: 自定义震动模式时,确保模式数组的长度为偶数,并且交替表示停止和震动的时间 (单位:毫秒)。
  • 推送通知配置: 如果使用推送通知,请确保推送 payload 中包含 sound 字段,并且服务器配置正确。 具体的配置方法取决于你使用的推送服务提供商 (例如:Firebase Cloud Messaging)。

总结

通过本文档,你应该能够成功地为你的 Expo 应用添加声音和震动通知功能。 记住,正确配置通知处理程序、加载和播放声音文件、触发设备震动以及处理权限是实现这一目标的关键。 如果你仍然遇到问题,请仔细检查你的代码和配置,并参考 Expo 和 React Native 的官方文档。

以上就是为 Expo 应用添加声音和震动通知的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号