Markus Olsson
Markus Olsson

Reputation: 197

Vibration on Xamarin Android

Im currently working on an application using Xamarin android. I cannot get the device to vibrate though.

Vibrator vibrator = (Vibrator)Activity.GetSystemService(Context.VibratorService);
vibrator.Vibrate(100);

It builds but crashes when I press the button that is linked to the code.

Upvotes: 8

Views: 10393

Answers (2)

Pranay Deep
Pranay Deep

Reputation: 1401

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

Open the AssemblyInfo.cs file under the Properties folder and add:

C#

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

OR

Update Android Manifest:

Open the AndroidManifest.xml file under the Properties folder and add the following inside of the manifest node.

XML

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

Or right click on the Android project and open the project's properties. Under Android Manifest find the Required permissions: area and check the VIBRATE permission. This will automatically update the AndroidManifest.xml file.

Add a reference to Xamarin.Essentials in your class:

using Xamarin.Essentials;

The Vibration functionality can be requested for a set amount of time or the default of 500 milliseconds.

try
{
    // Use default vibration length
    Vibration.Vibrate();

    // Or use specified time
    var duration = TimeSpan.FromSeconds(1);
    Vibration.Vibrate(duration);
}
catch (FeatureNotSupportedException ex)
{
    // Feature not supported on device
}
catch (Exception ex)
{
    // Other error has occurred.
}

Cancellation of device vibration can be requested with the Cancel method:

try
{
    Vibration.Cancel();
}
catch (FeatureNotSupportedException ex)
{
    // Feature not supported on device
}
catch (Exception ex)
{
    // Other error has occurred.
}

ref - https://learn.microsoft.com/en-us/xamarin/essentials/vibrate?tabs=android

Upvotes: 0

Dima
Dima

Reputation: 96

This solves the problem AndroidManifest.xml

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

Upvotes: 8

Related Questions