入门指南
-
安装包
Terminal window npm i @capgo/capacitor-shakeTerminal window pnpm add @capgo/capacitor-shakeTerminal window yarn add @capgo/capacitor-shakeTerminal window bun add @capgo/capacitor-shake -
与原生项目同步
Terminal window npx cap syncTerminal window pnpm cap syncTerminal window yarn cap syncTerminal window bunx cap sync -
配置插件
基本使用示例:
import { Shake } from '@capgo/capacitor-shake';// Start listening for shake gesturesawait Shake.start();// Listen for shake eventsShake.addListener('shake', () => {console.log('Device was shaken!');// Perform your action here});灵敏度配置:
// Configure shake sensitivityawait Shake.start({threshold: 3.5 // Adjust sensitivity (default: 3.5)});iOS 无需额外设置。
Android 无需额外设置。
-
停止监听摇动
// Stop shake detection when not neededawait Shake.stop();// Remove specific listenerconst handle = await Shake.addListener('shake', () => {console.log('Shaken!');});handle.remove(); -
示例实现
import { Shake } from '@capgo/capacitor-shake';import { App } from '@capacitor/app';export class ShakeService {private shakeListener: any;async initialize() {// Start shake detectionawait Shake.start({ threshold: 4.0 });// Add shake listenerthis.shakeListener = await Shake.addListener('shake', () => {this.handleShake();});// Clean up on app pauseApp.addListener('pause', () => {Shake.stop();});// Resume on app resumeApp.addListener('resume', () => {Shake.start({ threshold: 4.0 });});}private handleShake() {console.log('Shake detected!');// Show debug menu, refresh data, or trigger any action}async cleanup() {if (this.shakeListener) {this.shakeListener.remove();}await Shake.stop();}}
API 参考
Section titled “API 参考”start(options?: ShakeOptions)
Section titled “start(options?: ShakeOptions)”开始监听摇动手势。
参数:
options(可选):配置对象threshold: number - 灵敏度阈值(默认:3.5)
stop()
Section titled “stop()”停止监听摇动手势。
addListener('shake', callback: () => void)
Section titled “addListener('shake', callback: () => void)”添加摇动事件监听器。
返回: 带有删除监听器句柄的 Promise
interface ShakeOptions { threshold?: number; // Shake sensitivity threshold}- 使用设备的加速度计检测摇动手势
- 在前台和后台均可工作(如果应用具有后台权限)
Android
Section titled “Android”- 使用 SensorManager 检测摇动事件
- 不需要特殊权限
- 应用在前台时工作
- 调试菜单:设备摇动时显示开发者选项
- 反馈:触发反馈表单或错误报告
- 刷新:刷新应用数据或清除缓存
- 游戏:使用摇动作为游戏控制机制
- 撤销:实现摇动撤销功能
未检测到摇动:
- 确保使用
Shake.start()启动了插件 - 尝试调整阈值(较低 = 更敏感)
- 检查监听器是否正确注册
太敏感/不够敏感:
- 在
start()选项中调整threshold参数 - 值通常范围从 2.0(非常敏感)到 5.0(较不敏感)