DEV Community

HarmonyOS
HarmonyOS

Posted on

Starting and Stopping Vibration

Read the original article:Starting and Stopping Vibration

Requirement Description

Wearables and other HarmonyOS devices often rely on haptic feedback to enhance user experience. Developers may need to:

  • Trigger vibration feedback (short taps, long buzzes, custom vibration patterns).
  • Stop ongoing vibration when necessary.

The Vibrator Service Kit provides the APIs startVibration and stopVibration for these functions.

Background Knowledge

  • Module: @kit.SensorServiceKit
  • System Capability: SystemCapability.Sensors.MiscDevice
  • Supported Devices: Phone, PC/2in1, Tablet, TV, Wearable
  • Permissions Required: ohos.permission.VIBRATE
  • Quick App Support: Yes (API version ≥ 11)

Effect Types (VibrateEffect):

  • VibratePreset – Built-in vibration patterns for taps, long presses, etc.
  • VibrateFromFile – Uses vibration definition from custom configuration file (.json).
  • VibrateTime – Fixed-duration vibration (milliseconds).
  • VibrateFromPattern – Custom vibration sequence defined programmatically.

Stop Modes (VibratorStopMode):

  • VIBRATOR_STOP_MODE_TIME – Stop fixed-duration vibration.
  • VIBRATOR_STOP_MODE_PRESET – Stop preset vibration.

Error Codes:

  • 201: Permission denied.
  • 401: Parameter error (missing, incorrect type).
  • 801: Capability not supported.
  • 14600101: Device operation failed.

Implementation Steps

  1. Import Modules:
    • vibrator from @kit.SensorServiceKit
    • BusinessError from @kit.BasicServicesKit
    • resourceManager from @kit.LocalizationKit (for file-based effects)
  2. Request Permission: Add ohos.permission.VIBRATE in module.json5.
  3. Start Vibration using one of four modes:
    • Preset (effectId)
    • File (hapticFd)
    • Time (duration)
    • Pattern (array definition)
  4. Stop Vibration using the appropriate stop mode.
  5. Error Handling: Wrap in try/catch, log err.code and err.message.

Code Snippet (Time-Based)

import { vibrator } from '@kit.SensorServiceKit';
import { BusinessError } from '@kit.BasicServicesKit';

try {
  vibrator.startVibration({
    type: 'time',
    duration: 1000
  }, {
    id: 0,
    usage: 'alarm'
  }).then(() => {
    console.info('1-second vibration started');
  }, (error: BusinessError) => {
    console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`);
  });
} catch (err) {
  let e: BusinessError = err as BusinessError;
  console.error(`Unexpected error: ${e.code}, message: ${e.message}`);
}
Enter fullscreen mode Exit fullscreen mode

Stop Vibration (Time Mode) Code:

import { vibrator } from '@kit.SensorServiceKit';
import { BusinessError } from '@kit.BasicServicesKit';

try {
  vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME, (error: BusinessError) => {
    if (error) {
      console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`);
      return;
    }
    console.info('Vibration stopped successfully');
  });
} catch (err) {
  let e: BusinessError = err as BusinessError;
  console.error(`Unexpected error: ${e.code}, message: ${e.message}`);
}
Enter fullscreen mode Exit fullscreen mode

Test Results

  • On Wearable (Watch 5):
    • Preset vibration worked for tap feedback.
    • File-based vibration triggered a custom alarm pattern.
    • Time-based vibration ran for 1 second and stopped when stopVibration was called.
  • On PC (emulator):
    • Returned 801 (capability not supported).

Limitations or Considerations

  • Device-Dependent: Some vibration effects are not supported on all devices.
  • Performance: File-based and pattern-based vibration may consume more battery.
  • Permissions: Must include ohos.permission.VIBRATE.
  • Stop Mode: Use the correct stop mode (TIME, PRESET) to terminate vibration.

Related Documents

Written by Taha Enes Kon

Top comments (0)