Xamarin.Essentials:气压计Xamarin.Essentials: Barometer

Barometer 类可用于监视设备的气压计传感器,该传感器可测量压力。The Barometer class lets you monitor the device's barometer sensor, which measures pressure.

入门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.

使用 BarometerUsing Barometer

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

using Xamarin.Essentials;

Barometer 功能通过调用 StartStop 方法来侦听气压计压力读数的变化(以百帕为单位)。The Barometer functionality works by calling the Start and Stop methods to listen for changes to the barometer's pressure reading in hectopascals. 然后通过 ReadingChanged 事件反馈任何变化。Any changes are sent back through the ReadingChanged event. 示例用法如下:Here is sample usage:

public class BarometerTest
    // Set speed delay for monitoring changes.
    SensorSpeed speed = SensorSpeed.UI;

    public BarometerTest()
        // Register for reading changes.
        Barometer.ReadingChanged += Barometer_ReadingChanged;

    void Barometer_ReadingChanged(object sender, BarometerChangedEventArgs e)
        var data = e.Reading;
        // Process Pressure
        Console.WriteLine($"Reading: Pressure: {data.PressureInHectopascals} hectopascals");

    public void ToggleBarometer()
            if (Barometer.IsMonitoring)
        catch (FeatureNotSupportedException fnsEx)
            // Feature not supported on device
        catch (Exception ex)
            // Other error has occurred.

传感器速度Sensor Speed

  • 最快 – 尽快获取传感器数据(不保证在 UI 线程上返回)。Fastest – Get the sensor data as fast as possible (not guaranteed to return on UI thread).
  • 游戏 – 适合游戏的速度(不保证在 UI 线程上返回)。Game – Rate suitable for games (not guaranteed to return on UI thread).
  • 正常 – 适合屏幕方向更改的默认速率。Normal – Default rate suitable for screen orientation changes.
  • UI – 适合常规用户界面的速率。UI – Rate suitable for general user interface.

如果事件处理程序不能保证在 UI 线程上运行,并且如果事件处理程序需要访问用户界面元素,请使用 MainThread.BeginInvokeOnMainThread 方法在 UI 线程上运行该代码。If your event handler is not guaranteed to run on the UI thread, and if the event handler needs to access user-interface elements, use the MainThread.BeginInvokeOnMainThread method to run that code on the UI thread.

平台实现细节Platform Implementation Specifics

无特定于平台的实现细节。No platform-specific implementation details.