Bewerken

Delen via


Vibration

Browse sample. Browse the sample

This article describes how you can use the .NET Multi-platform App UI (.NET MAUI) IVibration interface. This interface lets you start and stop the vibrate functionality for a desired amount of time.

The default implementation of the IVibration interface is available through the Vibration.Default property. Both the IVibration interface and Vibration class are contained in the Microsoft.Maui.Devices namespace.

Get started

To access the Vibration functionality, the following platform specific setup is required.

The VIBRATE permission is required, and must be configured in the Android project. This permission can be added in the following ways:

  • Add the assembly-based permission:

    Open the Platforms/Android/MainApplication.cs file and add the following assembly attributes after using directives:

    [assembly: UsesPermission(Android.Manifest.Permission.Vibrate)]
    

    - or -

  • Update the Android Manifest:

    Open the Platforms/Android/AndroidManifest.xml file and add the following in the manifest node:

    <uses-permission android:name="android.permission.VIBRATE" />
    

    - or -

  • Update the Android Manifest in the manifest editor:

    In Visual Studio double-click on the Platforms/Android/AndroidManifest.xml file to open the Android manifest editor. Then, under Required permissions check the VIBRATE permission. This will automatically update the AndroidManifest.xml file.

Vibrate the device

The vibration functionality can be requested for a set amount of time or the default of 500 milliseconds. The following code example randomly vibrates the device between one and seven seconds using the Vibrate(TimeSpan):

private void VibrateStartButton_Clicked(object sender, EventArgs e)
{
    int secondsToVibrate = Random.Shared.Next(1, 7);
    TimeSpan vibrationLength = TimeSpan.FromSeconds(secondsToVibrate);
    
    Vibration.Default.Vibrate(vibrationLength);
}

private void VibrateStopButton_Clicked(object sender, EventArgs e) =>
    Vibration.Default.Cancel();

Platform differences

This section describes the platform-specific differences with the vibration API.

No platform differences.