示例工程【免费下载链接】Windows-universal-samplesAPI samples for the Universal Windows Platform.项目地址https://gitcode.com/gh_mirrors/wi/Windows-universal-samples点击查看免费下载本指南围绕 Windows-universal-samples 仓库中的 Pedometer 示例 展开系统讲解 Windows 10 UWP 平台下Windows.Devices.Sensors.PedometerAPI 的四种典型用法ReadingChanged 事件订阅、历史步数查询、当前步数获取以及基于步数目标的传感器后台任务触发。读完本文你将掌握 Pedometer 传感器从获取默认实例到后台触发的完整调用链并可直接对照仓库源码C# / C 双语言实现落地到自己的健康类应用中。示例概览与场景结构Pedometer 示例用于展示系统中默认计步器pedometer的事件与历史数据能力核心入口是 SampleConfiguration.cs它定义了四个场景页分别对应Events注册默认计步器的ReadingChanged事件实时显示读数对应 Scenario1_Events.xamlHistory使用 History API 按时间段或全部历史检索步数记录对应 Scenario2_History.xamlCurrent step count通过GetCurrentReadings获取当前各步态类型的累计步数对应 Scenario3_CurrentStepCount.xamlBackground Pedometer把步数目标step goal作为后台触发条件目标达成后唤醒后台任务对应 Scenario4_BackgroundTask.xaml该示例同时提供 C#cs目录与 C/CXcpp目录两个版本两者的场景划分与 XAML 页面结构完全一致本文以 C# 代码为主展开C 实现作为对照引用。数据模型PedometerReading 与 PedometerStepKind所有场景共享同一个数据模型。PedometerReading包含四类核心属性属性含义Timestamp本次读数产生的时间戳StepKind步态类型Unknown/Walking/RunningCumulativeSteps该步态类型下的累计步数CumulativeStepsDuration累计步数对应的累计时长TimeSpan步态类型由枚举PedometerStepKind定义示例代码在 Scenario1_Events.xaml.cs 中按三种类型分别维护独立的累计步数计数器UI 表格也按 Unknown / Walking / Running 三行展示各自的步数与时长。场景一订阅 ReadingChanged 事件这是最常见的实时计步用法。核心流程在 Scenario1_Events.xaml.cs 中// 异步获取默认计步器 pedometer await Pedometer.GetDefaultAsync(); if (null pedometer) { rootPage.NotifyUser(No pedometer available, NotifyType.ErrorMessage); } else { pedometer.ReportInterval pedometer.MinimumReportInterval; // 设置最小上报间隔 pedometer.ReadingChanged Pedometer_ReadingChanged; // 订阅读数变化事件 }事件处理函数Pedometer_ReadingChanged中通过args.Reading拿到PedometerReading按StepKind分流更新各步态类型的累计步数与时长同时累加得到总步数PedometerReading reading args.Reading; switch (reading.StepKind) { case PedometerStepKind.Walking: walkingStepCount reading.CumulativeSteps; ScenarioOutput_WalkingCount.Text walkingStepCount.ToString(); ScenarioOutput_WalkingDuration.Text reading.CumulativeStepsDuration.TotalMilliseconds.ToString(); break; // Unknown / Running 分支同理 } totalCumulativeSteps newCount;需要注意两点ReportInterval设置为MinimumReportInterval即以传感器硬件支持的最小间隔上报保证实时性取消订阅时只需pedometer.ReadingChanged - Pedometer_ReadingChanged。事件回调在非 UI 线程触发因此代码通过Dispatcher.RunAsync(CoreDispatcherPriority.Normal, ...)将 UI 更新封送到 UI 线程见 Scenario1_Events.xaml.cs。设备访问权限检查示例在场景一构造函数中通过设备类 ID 创建DeviceAccessInformation并监听AccessChangedGuid PedometerClassId new Guid(B19F89AF-E3EB-444B-8DEA-202575A71599); deviceAccessInformation DeviceAccessInformation.CreateFromDeviceClassId(PedometerClassId); deviceAccessInformation.AccessChanged AccessChanged;当权限状态变为非Allowed时UI 会提示 Access denied to pedometers 并重置注册状态Scenario1_Events.xaml.cs。同时GetDefaultAsync可能抛出UnauthorizedAccessException代码中也做了捕获处理。场景二检索步数历史记录History 场景演示了Pedometer历史 API 的两个重载见 Scenario2_History.xaml.cs重载一获取全部可用历史var dt DateTime.FromFileTimeUtc(0); // 文件时间起点1601-01-01 var fromBeginning new DateTimeOffset(dt); historyReadings await Pedometer.GetSystemHistoryAsync(fromBeginning);重载二按指定时间段获取TimeSpan span TimeSpan.FromTicks(toTime.Ticks - fromTime.Ticks); historyReadings await Pedometer.GetSystemHistoryAsync(fromTime, span);XAML 页面Scenario2_History.xaml提供两个单选按钮默认的Entire available history以及History within a specific range。后者展开 DatePicker TimePicker 组合让用户分别选择 From/To 的时间点。由于DateTimePicker会带入系统当前的时分秒代码用Calendar先清零 Nanosecond/Second/Minute/Hour 再叠加 TimePicker 的秒数得到精确的起止时间var calendar new Calendar(); calendar.ChangeClock(24HourClock); calendar.SetDateTime(FromDate.Date); calendar.AddNanoseconds(-calendar.Nanosecond); calendar.AddSeconds(-calendar.Second); calendar.AddMinutes(-calendar.Minute); calendar.AddHours(-calendar.Hour); calendar.AddSeconds(Convert.ToInt32(FromTime.Time.TotalSeconds)); DateTimeOffset fromTime calendar.GetDateTime();两个细节值得注意时间合法性校验若toTime.ToFileTime() fromTime.ToFileTime()会提示 Invalid time span. To Time must be equal or more than From TimeScenario2_History.xaml.cs。结果截断展示示例将返回的记录绑定到 ListView并最多展示 100 条if (historyRecords.Count 100) break;每条记录通过HistoryRecord包装类时间戳、步态类型、步数、时长四个展示字段呈现UI 列头依次为 Time Stamp / Step Kind / Steps Count / Steps Duration。注意历史查询返回的是同一时刻不同步态类型的多条记录传感器在某个时间点会同时产出 Unknown、Walking、Running 各自的读数。这一点在场景四的后台任务解析中尤为关键。场景三获取当前步数当用户静止不动时ReadingChanged不会被触发因此无法依赖事件获取当前步数。示例专门演示了GetCurrentReadingsAPIScenario3_CurrentStepCount.xaml.csvar sensor await Pedometer.GetDefaultAsync(); if (sensor ! null) { var currentReadings sensor.GetCurrentReadings(); // 返回 DictionaryPedometerStepKind, PedometerReading int totalStepCount 0; foreach (PedometerStepKind kind in Enum.GetValues(typeof(PedometerStepKind))) { PedometerReading reading; if (currentReadings.TryGetValue(kind, out reading)) { totalStepCount reading.CumulativeSteps; } } ScenarioOutput_TotalStepCount.Text totalStepCount.ToString(); }GetCurrentReadings()返回IReadOnlyDictionaryPedometerStepKind, PedometerReading把三种步态类型各自的累计步数相加即可得到当前总步数。与历史 API 一样调用前同样先通过DeviceAccessInformation.CreateFromDeviceClassId(PedometerClassId)检查CurrentStatus DeviceAccessStatus.Allowed。场景四以步数目标为条件的后台任务这是示例中最有特色的部分把再走 50 步作为后台触发条件。前台页面负责注册后台任务负责在触发后回传读数。前台注册流程Scenario4核心逻辑在 Scenario4_BackgroundTask.xaml.csconst int stepGoalOffset 50; // 从当前步数再增加 50 步作为目标 // 1. 获取当前总步数 var currentReadings sensor.GetCurrentReadings(); int stepCount 0; foreach (PedometerStepKind kind in Enum.GetValues(typeof(PedometerStepKind))) { PedometerReading reading; if (currentReadings.TryGetValue(kind, out reading)) { stepCount reading.CumulativeSteps; } } // 2. 计算步数目标并构造数据阈值 stepGoal stepCount stepGoalOffset; var threshold new PedometerDataThreshold(sensor, stepGoal); var trigger new SensorDataThresholdTrigger(threshold); // 3. 构建并注册后台任务 var builder new BackgroundTaskBuilder() { Name SampleBackgroundTaskName, // Scenario4_PedometerBackgroundTask TaskEntryPoint SampleBackgroundTaskEntryPoint // Tasks.PedometerBackgroundTask }; builder.SetTrigger(trigger); BackgroundTaskRegistration task builder.Register(); task.Completed OnCompleted;注册前需要向系统申请后台访问权限var status await BackgroundExecutionManager.RequestAccessAsync(); if ((BackgroundAccessStatus.AlwaysAllowed status) || (BackgroundAccessStatus.AllowedSubjectToSystemPolicy status)) { RegisterBackgroundTask(); }前台还通过BackgroundTaskRegistration.AllTasks检查同名任务是否已注册并在页面加载时恢复状态页面提供 Unregister 按钮通过cur.Value.Unregister(true /*cancelTask*/)注销任务。关键点一次性触发的语义SensorDataThresholdTrigger是一次性one-shot触发步数目标达成即触发一次之后不会再因步数变化而触发。因此示例在OnCompleted回调中主动注销任务Scenario4_BackgroundTask.xaml.csprivate void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args) { string status Completed and Unregistered; try { args.CheckResult(); } catch (Exception e) { status e.Message; } // Pedometer background triggers are one-shot - 触发后即失效 task.Unregister(false); backgroundTaskRegistered false; UpdateUIAsync(status); }注释明确指出一旦原始注册关联的步数目标达成该步数即为过去式不会随步数继续变化再次触发所以要么注销任务要么更新步数目标重新注册。后台任务实现Tasks 项目后台任务位于独立的 Tasks 工程C# 实现见 PedometerBackgroundTask.cspublic void Run(IBackgroundTaskInstance taskInstance) { taskInstance.Canceled OnCanceled; SensorDataThresholdTriggerDetails triggerDetails taskInstance.TriggerDetails as SensorDataThresholdTriggerDetails; if (SensorType.Pedometer triggerDetails.SensorType) { var reports Pedometer.GetReadingsFromTriggerDetails(triggerDetails); var settings ApplicationData.Current.LocalSettings; var lastReading reports[reports.Count - 1]; settings.Values[ReportCount] reports.Count.ToString(); settings.Values[LastTimestamp] lastReading.Timestamp; settings.Values[lastReading.StepKind.ToString()] lastReading.CumulativeSteps.ToString(); // ... settings.Values[TaskStatus] Completed at DateTime.Now.ToString(u); } }关键机制Pedometer.GetReadingsFromTriggerDetails(triggerDetails)从触发详情中取出一组读数——触发瞬间传感器会同时产出多个步态类型的读数。这些读数共享相同的时间戳knownTimestamp代码从最后一个读数向前遍历把同一时间戳下各StepKind的CumulativeSteps逐一写入ApplicationData.Current.LocalSettings供前台应用读取PedometerBackgroundTask.cs。OnCanceled回调同样把取消原因写入 LocalSettings记录TaskStatus。由于任务只做数据写入、立即返回示例不持有 deferralNo deferral is held on taskInstance。C/CX 版本在 PedometerBackgroundTask.cpp 中实现了完全相同的逻辑只是通过reports-GetAt(reports-Size - nThFromLast)倒序遍历并用timestampFormatter格式化时间戳。前台场景四的UpdateUIAsyncScenario4_BackgroundTask.xaml.cs从 LocalSettings 中读取ReportCount、TaskStatus、LastTimestamp以及各 StepKind 计数并刷新 UI实现后台数据到前台界面的回传。后台任务清单声明后台任务必须在应用清单中声明cs/Package.appxmanifest 中的关键片段Extensions Extension Categorywindows.backgroundTasks EntryPointTasks.PedometerBackgroundTask BackgroundTasks Task Typegeneral / /BackgroundTasks /Extension /Extensions同时清单声明了activity设备功能权限DeviceCapability Nameactivity /这是访问步数历史等活动数据所必需的目标设备族为Windows.UniversalMinVersion10.0.10586.0。构建与运行示例的构建运行方式遵循 UWP 示例通用流程详见 Pedometer README系统要求Windows 10建议使用带计步硬件的设备如手机或部分平板模拟器/桌面环境可能返回无计步器可用。构建步骤若以 ZIP 方式下载整个示例集合必须解压整个归档不要只解压示例所在文件夹以保证 SharedContent 共享依赖可用。启动 Visual Studio选择File Open Project/Solution。进入Samples子目录 → 本示例子目录 → 选择语言子目录cs或cpp双击其中的解决方案文件如 Pedometer.sln。注意解决方案同时包含主应用工程与 Tasks 后台任务工程。按CtrlShiftB或Build Build Solution生成。运行步骤仅部署选择Build Deploy Solution。部署并调试运行按F5或Debug Start Debugging不调试直接运行按CtrlF5或Debug Start Without Debugging。相关主题原文档还关联了 JavaScript已归档版本的 Pedometer 示例该版本位于archived目录可作为历史参考当前主版本以 C# 与 C 实现为准。小结Pedometer 示例覆盖了计步传感器应用的核心闭环实时订阅ReadingChanged→ 历史检索GetSystemHistoryAsync 双重载→ 当前读数GetCurrentReadings→ 后台触发PedometerDataThreshold SensorDataThresholdTrigger。其中后台场景中同一时间戳多条读数的解析方式前台按步态分表展示、后台任务按时间戳归并写入 LocalSettings是理解 Pedometer 数据模型的钥匙而一次性触发语义则提醒开发者在目标达成后务必注销或重置后台任务。对照 cs 与 cpp 两套实现可以快速掌握该 API 在托管与原生两种语言体系下的完整用法。赞分享示例工程【免费下载链接】Windows-universal-samplesAPI samples for the Universal Windows Platform.项目地址https://gitcode.com/gh_mirrors/wi/Windows-universal-samples点击查看免费下载相关推荐magnetW API文档示例项目完整使用场景magnetW API文档示例项目完整使用场景 你是否在开发中遇到过API接口设计混乱、文档与实际代码脱节、用户难以快速上手的问题本文将通过magnetW项桌面应用网页爬虫使用 Terraform AWS Provider 构建 API Gateway WebSocket 聊天应用完整示例解析使用 Terraform AWS Provider 构建 API Gateway WebSocket 聊天应用完整示例解析 导读 本文以 terraformIaC云原生基础设施UWP 文件选择器全场景实战Windows-universal-samples FilePicker 示例深度解析UWP 文件选择器全场景实战Windows universal samples FilePicker 示例深度解析 导读 本文基于 Windows unive示例工程上一篇Arize Phoenix项目核心技术解析与应用指南下一篇Express-Validator 自定义错误消息完全指南创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
企业数字化 ERP 产品动态
相关推荐
Rematch 入门:以无样板代码的方式构建 Redux 框架的 Redux Store 前端 【免费下载链接】rematch The Redux Framework 项目地址: https://gitcode.com/gh_mirrors/re/rematch 点击查看 免费下载 本文基于 Rematch 仓库的介绍文档(docs/introduction.md)展开:Rematch 定位为“不带样板代码的 Red… · 2026/9/25 2:40:16
SQL Server 评估 API 数据转换之 rename:列重命名的配置语法与实战 示例工程数据库教程后端 【免费下载链接】sql-server-samples Azure Data SQL Samples - Official Microsoft GitHub Repository containing code samples for SQL Server, Azure SQL, Azure Synapse, and Azure SQL Edge 项目地址: https://gitcode.com/gh_mirrors… · 2026/9/25 2:40:16
基于Python的豆瓣电影情感分析推荐系统设计 1. 需求拆解与整体架构:这个系统到底解决什么问题说起电影推荐,很多人第一反应是豆瓣的“猜你喜欢”。但实际用过的人都知道,这个功能隔三差五给你推一些评分很高、口碑爆棚的电影,点进去看了才发现根本不是你的菜。评分高不代表你… · 2026/9/25 3:06:26
全栈AI修图Agent:从意图理解到可控生成的落地实践 1. 这不是又一个“AI修图网页”,而是一套可落地的全栈Agent工作流“又一个新项目完结,全栈 AI 修图 Agent!”——这句话我发在技术群里的时候,有朋友回:“修图?不就是调个 Stable Diffusion API,… · 2026/9/25 3:06:20
NodeGui QStandardItem 深度指南:从模型/视图架构到数据、状态与标志位控制 桌面应用跨平台 【免费下载链接】nodegui A library for building cross-platform native desktop applications with Node.js and CSS 🚀. React NodeGui : https://react.nodegui.org and Vue NodeGui: https://vue.nodegui.org 项目地址: https://git… · 2026/9/25 3:06:20
WPScan 插件版本指纹实战:从 Media Credit 的 CHANGELOG.md 看动态查找器如何识别插件版本 网络安全漏洞扫描渗透测试应用安全CLI 【免费下载链接】wpscan WPScan WordPress security scanner. Written for security professionals and blog maintainers to test the security of their WordPress websites. Contact us via contactwpscan.com 项目地址: ht… · 2026/9/25 3:06:14
可信AI赋能芯片签核:从黑盒预测到可验证决策 1. 签核为何需要"可信AI":黑盒模型的天花板不是性能,是信任芯片行业这两年聊AI聊得特别多,从RTL自动生成到版图布线,到处都是AI的影子。但如果你真在fabless公司或者Foundry干过签核(Sign-off)这… · 2026/9/25 3:06:14
创维E900V22D刷机全攻略:S905L3SB芯片兼容性解析与救砖实战 /* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views … · 2026/9/25 1:00:31
MQTT协议原理与Broker服务器搭建实战:从Mosquitto到EMQX /* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views … · 2026/9/25 1:00:37