设备信息

Browse sample. 浏览示例

本文介绍如何使用 .NET Multi-platform App UI (.NET MAUI) IDeviceInfo 接口读取有关应用运行所在设备的信息。

IDeviceInfo 接口的默认实现通过 DeviceInfo.Current 属性提供。 IDeviceInfo 接口和 DeviceInfo 类都包含在 Microsoft.Maui.Devices 命名空间中。

读取设备信息

IDeviceInfo 接口提供许多描述设备的属性,例如制造商与外观。 下面示例展示如何读取设备信息属性:

private void ReadDeviceInfo()
{
    System.Text.StringBuilder sb = new System.Text.StringBuilder();

    sb.AppendLine($"Model: {DeviceInfo.Current.Model}");
    sb.AppendLine($"Manufacturer: {DeviceInfo.Current.Manufacturer}");
    sb.AppendLine($"Name: {DeviceInfo.Current.Name}");
    sb.AppendLine($"OS Version: {DeviceInfo.Current.VersionString}");
    sb.AppendLine($"Idiom: {DeviceInfo.Current.Idiom}");
    sb.AppendLine($"Platform: {DeviceInfo.Current.Platform}");

    bool isVirtual = DeviceInfo.Current.DeviceType switch
    {
        DeviceType.Physical => false,
        DeviceType.Virtual => true,
        _ => false
    };

    sb.AppendLine($"Virtual device? {isVirtual}");

    DisplayDeviceLabel.Text = sb.ToString();
}

获取设备平台

IDeviceInfo.Platform 属性表示应用运行所在的操作系统。 DevicePlatform 类型为每个操作系统提供一个属性:

下面示例展示如何检查 IDeviceInfo.Platform 属性是否与 Android 操作系统匹配:

private bool IsAndroid() =>
    DeviceInfo.Current.Platform == DevicePlatform.Android;

获取设备类型

IDeviceInfo.Idiom 属性表示应用运行所在设备的类型,例如台式计算机或平板电脑。 DeviceIdiom 类型为每种设备类型提供一个属性:

下面的示例展示如何将 IDeviceInfo.Idiom 值与 DeviceIdiom 属性比较:

private void PrintIdiom()
{
    if (DeviceInfo.Current.Idiom == DeviceIdiom.Desktop)
        Console.WriteLine("The current device is a desktop");
    else if (DeviceInfo.Current.Idiom == DeviceIdiom.Phone)
        Console.WriteLine("The current device is a phone");
    else if (DeviceInfo.Current.Idiom == DeviceIdiom.Tablet)
        Console.WriteLine("The current device is a Tablet");
}

设备类型

IDeviceInfo.DeviceType 属性,一种确定应用程序是在物理设备还是虚拟设备上运行的枚举。 虚拟设备是指模拟器或仿真程序。

bool isVirtual = DeviceInfo.Current.DeviceType switch
{
    DeviceType.Physical => false,
    DeviceType.Virtual => true,
    _ => false
};

平台差异

本部分使用设备信息介绍特定于平台的差异。

无平台差异。