简体   繁体   English

Xamarin Android 上的振动

[英]Vibration on Xamarin Android

Im currently working on an application using Xamarin android.我目前正在使用Xamarin android 开发一个应用程序。 I cannot get the device to vibrate though.我无法让设备vibrate

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.振动权限是必需的,必须在Android项目中配置。 This can be added in the following ways:这可以通过以下方式添加:

Open the AssemblyInfo.cs file under the Properties folder and add:打开 Properties 文件夹下的 AssemblyInfo.cs 文件并添加:

C# C#

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

OR或者

Update Android Manifest :更新 Android 清单

Open the AndroidManifest.xml file under the Properties folder and add the following inside of the manifest node.打开 Properties 文件夹下的 AndroidManifest.xml 文件,并在 manifest 节点中添加以下内容。

XML XML

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

Or right click on the Android project and open the project's properties.或者右键单击Android 项目并打开项目的属性。 Under Android Manifest find the Required permissions: area and check the VIBRATE permission.在 Android Manifest 下找到所需的权限:区域并检查 VIBRATE 权限。 This will automatically update the AndroidManifest.xml file.这将自动更新 AndroidManifest.xml 文件。

Add a reference to Xamarin.Essentials in your class:在类中添加对 Xamarin.Essentials 的引用:

using Xamarin.Essentials;

The Vibration functionality can be requested for a set amount of time or the default of 500 milliseconds.可以在设定的时间或默认 500 毫秒内请求振动功能。

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:可以使用 Cancel 方法请求取消设备振动:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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