在 HarmonyOS 中,实现振动功能可以通过调用设备的振动器服务来完成。HarmonyOS 提供了相关的 API 来控制设备的振动。

下面是一个详细的示例,演示如何在你的应用中实现振动功能。


使用 @ohos.vibrator 模块

HarmonyOS 提供的 @ohos.vibrator 模块用于控制设备的振动器。


示例代码(JS/ArkTS)

确保你已经在项目中引入了 @ohos.vibrator 模块。


{
    "name": "entry",
    "type": "page",
    "module": {
        "package": "com.example.harmonyvibrator",
        "main": "index",
        "js": {
            "path": "dist"
        },
        "pages": [
            "pages/index"
        ],
        "dependencies": {
            "@ohos.application": "*",
            "@ohos.vibrator": "*"
        }
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.

在你的页面中使用振动器模块。


import vibrator from '@ohos.vibrator';

@Component
struct MainPage {
    build() {
        Column() {
            Button("Vibrate for 1000ms")
                .onClick(() => {
                    this.startVibration(1000);
                });

            Button("Cancel Vibration")
                .onClick(() => {
                    this.cancelVibration();
                });
        }
    }

    startVibration(duration: number) {
        vibrator.vibrate(duration)
            .then(() => {
                console.log(`Vibration started for ${duration} ms`);
            })
            .catch((err) => {
                console.error('Failed to start vibration:', err);
            });
    }

    cancelVibration() {
        vibrator.cancel()
            .then(() => {
                console.log('Vibration cancelled');
            })
            .catch((err) => {
                console.error('Failed to cancel vibration:', err);
            });
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.

解释

vibrator.vibrate(duration):

启动振动,持续时间为 duration 毫秒。

该方法返回一个 Promise,你可以通过 .then 和 .catch 方法来处理成功和失败的情况。

vibrator.cancel():

取消当前的振动操作,同样返回一个 Promise,用于处理操作结果。

权限配置

确保你的应用具有使用振动功能的权限。在 config.json 文件中添加以下权限配置:


{
    "module": {
        "reqPermissions": [
            {
                "name": "ohos.permission.VIBRATE"
            }
        ]
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

总结

通过使用 HarmonyOS 提供的 @ohos.vibrator 模块,可以方便地在应用中实现振动功能。

上面的示例展示了如何启动和取消振动,并且包含了必要的权限配置。