Haptic feedback
This article describes how you can use the .NET Multi-platform App UI (.NET MAUI) IHapticFeedback interface to control haptic feedback on a device. Haptic feedback is generally manifested by a gentle vibration sensation provided by the device to give a response to the user. Some examples of haptic feedback are when a user types on a virtual keyboard or when they play a game where the player's character has an encounter with an enemy character.
The default implementation of the IHapticFeedback
interface is available through the HapticFeedback.Default property. Both the IHapticFeedback
interface and HapticFeedback
class are contained in the Microsoft.Maui.Devices
namespace.
Get started
To access the haptic feedback functionality, the following platform-specific setup is required.
The Vibrate
permission is required and must be configured in the Android project. This 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.
Use haptic feedback
The haptic feedback functionality is performed in two modes: a short Click or a LongPress. The following code example initiates a Click
or LongPress
haptic feedback response to the user based on which Button they click:
private void HapticShortButton_Clicked(object sender, EventArgs e) =>
HapticFeedback.Default.Perform(HapticFeedbackType.Click);
private void HapticLongButton_Clicked(object sender, EventArgs e) =>
HapticFeedback.Default.Perform(HapticFeedbackType.LongPress);