boxmoe_header_banner_img

Hello! 欢迎来到悠悠畅享网!

文章导读

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


avatar
作者 2025年8月22日 21

为 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 的官方文档。



评论(已关闭)

评论已关闭