简体   繁体   中英

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.

这就解决了AndroidManifest.xml的问题

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

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://docs.microsoft.com/en-us/xamarin/essentials/vibrate?tabs=android

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM