在移动应用开发中,一款真正优秀的应用往往能够“感知”周围的环境——知道用户当前使用的设备型号、网络状态、地理位置,甚至能够响应设备的运动变化。这种感知能力不仅提升了用户体验,也为开发者提供了丰富的交互可能性。在 .NET MAUI 中,这一能力由 Essentials 库提供,它封装了数十种设备功能与传感器 API,让跨平台调用变得异常简单。本文将带你深入掌握 Essentials 的核心功能,并通过实战案例展示如何将这些能力融入你的应用。
13.1 设备信息:认识用户手中的设备
了解设备的硬件和系统信息,是应用适配和个性化功能的基础。DeviceInfo 类提供了设备的品牌、型号、操作系统版本等关键数据,而 DeviceDisplay 则让我们获取屏幕的物理尺寸和密度。
csharp
using Microsoft.Maui.Devices;
// 设备基础信息
string model = DeviceInfo.Current.Model; // 例如 "Pixel 5"
string manufacturer = DeviceInfo.Current.Manufacturer; // 例如 "Google"
string deviceName = DeviceInfo.Current.Name; // 用户设置的设备名称
string version = DeviceInfo.Current.VersionString; // 例如 "13"
string platform = DeviceInfo.Current.Platform.ToString(); // Android / iOS / WinUI
// 屏幕信息
var displayInfo = DeviceDisplay.Current.MainDisplayInfo;
double screenWidth = displayInfo.Width; // 物理宽度(像素)
double screenHeight = displayInfo.Height; // 物理高度(像素)
double density = displayInfo.Density; // 屏幕密度(用于像素到独立单位的转换)
// 判断是否为平板(根据宽度和密度综合判断,这里仅为示例)
bool isTablet = Math.Min(screenWidth, screenHeight) / density > 600;
💡 应用场景:根据设备类型(手机/平板)加载不同的布局;根据屏幕密度提供不同分辨率的图片;针对特定厂商的设备进行兼容性处理。
注意事项:DeviceInfo.Current.Platform 返回的是 DevicePlatform 枚举,可直接用于平台判断,例如 if (DeviceInfo.Current.Platform == DevicePlatform.Android) { ... }。
13.2 网络连接状态:做聪明的联网应用
移动网络环境复杂多变,应用需要能够实时感知网络状态并做出响应。Connectivity 类提供了网络访问检测和连接类型识别功能,并支持监听网络变化。
检测当前网络
csharp
using Microsoft.Maui.Networking;
var access = Connectivity.Current.NetworkAccess;
if (access == NetworkAccess.Internet)
{
// 已连接到互联网
var profiles = Connectivity.Current.ConnectionProfiles;
if (profiles.Contains(ConnectionProfile.WiFi))
{
// WiFi 连接,适合大流量操作
}
else if (profiles.Contains(ConnectionProfile.Cellular))
{
// 蜂窝网络,注意流量消耗


420

被折叠的 条评论
为什么被折叠?



