Cordova - 震动
Cordova - 震动 (Vibration)
Section titled “Cordova - 震动 (Vibration)”cordova-plugin-vibration 插件允许您的应用与设备的震动硬件进行交互。这可以用于为用户操作或通知提供触觉反馈(haptic feedback)。
注意:震动支持和行为在不同平台和设备上可能有所差异。有些设备可能不具备震动功能,或者用户可能禁用了它。
步骤 1 - 安装震动插件
Section titled “步骤 1 - 安装震动插件”要使用震动 API,首先需要将插件添加到您的 Cordova 项目中。打开终端(terminal)或命令提示符(command prompt)并运行:
cordova plugin add cordova-plugin-vibration步骤 2 - 添加 UI 元素(按钮)
Section titled “步骤 2 - 添加 UI 元素(按钮)”让我们在 index.html 中添加几个按钮来触发不同的震动效果。
<!-- 在 index.html 中 --><button id="simpleVibrateButton">Vibrate (3 Secs)</button><button id="patternVibrateButton">Vibrate Pattern</button><button id="cancelVibrateButton">Cancel Vibration</button>步骤 3 - 添加事件监听器
Section titled “步骤 3 - 添加事件监听器”在您的 index.js(或等效的 JavaScript 文件)中,为这些按钮设置事件监听器(event listeners)。确保这在 deviceready 事件之后完成。
// 在 index.js 中,'deviceready' 之后document.addEventListener('deviceready', () => { document.getElementById("simpleVibrateButton").addEventListener("click", simpleVibrate); document.getElementById("patternVibrateButton").addEventListener("click", patternVibrate); document.getElementById("cancelVibrateButton").addEventListener("click", cancelVibration);}, false);}步骤 4 - 实现震动函数
Section titled “步骤 4 - 实现震动函数”navigator.vibrate() 方法用于控制设备震动。它是 HTML5 Vibration API 的一部分,此插件对此进行了封装暴露。
要让设备震动指定的时长(以毫秒为单位):
function simpleVibrate() { // 震动 3000 毫秒 (3 秒) if (navigator.vibrate) { navigator.vibrate(3000); console.log('Vibrating for 3 seconds...'); } else { console.warn('Vibration API not supported on this device.'); alert('Vibration not supported.'); }}要以模式(一个包含震动和暂停时长的数组)进行震动:
function patternVibrate() { // 震动 1 秒,暂停 1 秒,震动 1 秒,暂停 1 秒,震动 1 秒 // 模式 (Pattern): [震动时长, 暂停时长, 震动时长, 暂停时长, 震动时长, ...] const pattern = [1000, 1000, 1000, 1000, 1000]; if (navigator.vibrate) { navigator.vibrate(pattern); console.log('Vibrating with pattern:', pattern); } else { console.warn('Vibration API not supported on this device.'); alert('Vibration not supported.'); }}要取消任何正在进行的震动:
function cancelVibration() { // 传入 0、一个空数组或一个只包含 0 的数组来取消 if (navigator.vibrate) { navigator.vibrate(0); // 或者: navigator.vibrate([]); console.log('Vibration cancelled.'); } else { console.warn('Vibration API not supported on this device.'); }}重要注意事项
Section titled “重要注意事项”请参考官方 cordova-plugin-vibration 文档和 MDN Web Docs 关于 Vibration API 的内容以获取更详细信息。