(予め)本記事はプレビュー版の環境に基づいて書かれています。
Windows 1o Desctop Build 10240
Windows 1o Mobile Build 10166
Visual Studio 2015 RC
製品版では内容と異なる可能性もあります。
紹介したプロジェクトは以下から実行可能です。
UWPアプリのサンプル(GitHub)
バックグラウンドでセンサーを利用する
バックグラウンド系2回目。前回はバックグラウンドにアプリが回ってもオーディオを止めないというものでした。
今回はバックグラウンドでセンサーを利用するサンプルです。
マニフェストファイルに記載
Package.appxmanifestにバックグラウンドタスクを記載。
<Extension Category="windows.backgroundTasks" EntryPoint="BackgroundTask.Scenario1_BackgroundTask"> <BackgroundTasks> <Task Type="deviceUse" /> </BackgroundTasks> </Extension>
バックグラウンドタスクの登録
バックグランドタスクを登録するコードは以下。
// Make sure only 1 task is running. FindAndCancelExistingBackgroundTask(); // Register the background task. var backgroundTaskBuilder = new BackgroundTaskBuilder() { Name = SampleConstants.Scenario1_DeviceUse_TaskName, TaskEntryPoint = SampleConstants.Scenario1_DeviceUse_TaskEntryPoint }; backgroundTaskBuilder.SetTrigger(_deviceUseTrigger); _deviceUseBackgroundTaskRegistration = backgroundTaskBuilder.Register(); // Make sure we're notified when the task completes or if there is an update. _deviceUseBackgroundTaskRegistration.Completed += new BackgroundTaskCompletedEventHandler(OnBackgroundTaskCompleted); try { // Request a DeviceUse task to use the accelerometer. DeviceTriggerResult deviceTriggerResult = await _deviceUseTrigger.RequestAsync(deviceId); switch (deviceTriggerResult) { case DeviceTriggerResult.Allowed: rootPage.NotifyUser("Background task started", NotifyType.StatusMessage); started = true; break; case DeviceTriggerResult.LowBattery: rootPage.NotifyUser("Insufficient battery to run the background task", NotifyType.ErrorMessage); break; case DeviceTriggerResult.DeniedBySystem: // The system can deny a task request if the system-wide DeviceUse task limit is reached. rootPage.NotifyUser("The system has denied the background task request", NotifyType.ErrorMessage); break; default: rootPage.NotifyUser("Could not start the background task: " + deviceTriggerResult, NotifyType.ErrorMessage); break; } }
バックグランドで行われる処理の実装はBackgroundTaskプロジェクトのScenario1_BackgroundTask.cs。
Runメソッドで加速度計を初期化、イベントハンドラ―の登録。
public void Run(IBackgroundTaskInstance taskInstance) { Accelerometer = Accelerometer.GetDefault(); if (null != Accelerometer) { SampleCount = 0; // Select a report interval that is both suitable for the purposes of the app and supported by the sensor. uint minReportIntervalMsecs = Accelerometer.MinimumReportInterval; Accelerometer.ReportInterval = minReportIntervalMsecs > 16 ? minReportIntervalMsecs : 16; // Subscribe to accelerometer ReadingChanged events. Accelerometer.ReadingChanged += new TypedEventHandler<Accelerometer, AccelerometerReadingChangedEventArgs>(ReadingChanged); // Take a deferral that is released when the task is completed. Deferral = taskInstance.GetDeferral(); // Get notified when the task is canceled. taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled); // Store a setting so that the app knows that the task is running. ApplicationData.Current.LocalSettings.Values["IsBackgroundTaskActive"] = true; } }
加速度計の値の変更にあわせてローカルストレージを書き替え。
private void ReadingChanged(object sender, AccelerometerReadingChangedEventArgs e) { SampleCount++; // Save the sample count if the foreground app is visible. bool appVisible = (bool)ApplicationData.Current.LocalSettings.Values["IsAppVisible"]; if (appVisible) { ApplicationData.Current.LocalSettings.Values["SampleCount"] = SampleCount; } }
Please give us your valuable comment