Xamarin.Essentials:振动: Vibration

Vibration 类使你能够在所需的时间内启动和停止振动功能。The Vibration class lets you start and stop the vibrate functionality for a desired amount of time.

入门Get started

若要开始使用此 API,请阅读 Xamarin.Essentials 的入门指南以确保在项目中正确安装和设置库。To start using this API, read the getting started guide for Xamarin.Essentials to ensure the library is properly installed and set up in your projects.

若要访问 Vibration 功能,需要以下特定于平台的设置。To access the Vibration functionality the following platform specific setup is required.

需要具有 Vibrate 权限,并且必须在 Android 项目中进行配置。The Vibrate permission is required and must be configured in the Android project. 可以通过以下方法添加此权限:This can be added in the following ways:

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

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

或更新 Android 清单:OR Update Android Manifest:

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

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

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

使用 VibrationUsing Vibration

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

using Xamarin.Essentials;

可以通过设置所需的时间量或使用默认 500 毫秒来使用 Vibration 功能。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.
}

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

平台差异Platform Differences

无平台差异。No platform differences.

APIAPI

第 9 频道YouTube 上查找更多 Xamarin 视频。Find more Xamarin videos on Channel 9 and YouTube.