次の方法で共有


光センサーの使用

環境光センサーを使って環境光の変化を検出する方法を説明します。

重要な API

前提条件

Extensible Application Markup Language (XAML)、Microsoft Visual C#、イベントについて理解している必要があります。

使うデバイスやエミュレーターが環境光センサーをサポートしている必要があります。

シンプルな光センサー アプリを作成する

ユーザーの環境の変化に反応するアプリを作成するための環境センサーは各種存在しますが、環境光センサーはその中の 1 つです。

Note

より完全な実装については、光センサーのサンプルをご覧ください。

手順

  • [Visual C#] プロジェクト テンプレートから [空白のアプリ (ユニバーサル Windows] を選んで、新しいプロジェクトを作成します。

  • プロジェクトの BlankPage.xaml.cs ファイルを開き、記載されているコードを次のコードで置き換えます。

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using Windows.Foundation;
    using Windows.Foundation.Collections;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Controls.Primitives;
    using Windows.UI.Xaml.Data;
    using Windows.UI.Xaml.Input;
    using Windows.UI.Xaml.Media;
    using Windows.UI.Xaml.Navigation;

    using Windows.UI.Core; // Required to access the core dispatcher object
    using Windows.Devices.Sensors; // Required to access the sensor platform and the ALS

    // The Blank Page item template is documented at https://go.microsoft.com/fwlink/p/?linkid=234238

    namespace App1
    {
        /// <summary>
        /// An empty page that can be used on its own or navigated to within a Frame.
        /// </summary>
        public sealed partial class BlankPage : Page
        {
            private LightSensor _lightsensor; // Our app' s lightsensor object

            // This event handler writes the current light-sensor reading to
            // the textbox named "txtLUX" on the app' s main page.

            private void ReadingChanged(object sender, LightSensorReadingChangedEventArgs e)
            {
                Dispatcher.RunAsync(CoreDispatcherPriority.Normal, (s, a) =>
                {
                    LightSensorReading reading = (a.Context as LightSensorReadingChangedEventArgs).Reading;
                    txtLuxValue.Text = String.Format("{0,5:0.00}", reading.IlluminanceInLux);
                });
            }

            public BlankPage()
            {
                InitializeComponent();
                _lightsensor = LightSensor.GetDefault(); // Get the default light sensor object

                // Assign an event handler for the ALS reading-changed event
                if (_lightsensor != null)
                {
                    // Establish the report interval for all scenarios
                    uint minReportInterval = _lightsensor.MinimumReportInterval;
                    uint reportInterval = minReportInterval > 16 ? minReportInterval : 16;
                    _lightsensor.ReportInterval = reportInterval;

                    // Establish the even thandler
                    _lightsensor.ReadingChanged += new TypedEventHandler<LightSensor, LightSensorReadingChangedEventArgs>(ReadingChanged);
                }

            }

        }
    }

元のスニペットの名前空間の名前を、自分のプロジェクトに指定した名前に変更する必要があります。 たとえば、作成したプロジェクトの名前が LightingCS だとすると、namespace App1namespace LightingCS に置き換えます。

  • MainPage.xaml ファイルを開き、元の内容を次の XML に置き換えます。
    <Page
        x:Class="App1.BlankPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="using:App1"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d">

        <Grid x:Name="LayoutRoot" Background="Black">
            <TextBlock HorizontalAlignment="Left" Height="44" Margin="52,38,0,0" TextWrapping="Wrap" Text="LUX Reading" VerticalAlignment="Top" Width="150"/>
            <TextBlock x:Name="txtLuxValue" HorizontalAlignment="Left" Height="44" Margin="224,38,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="217"/>


        </Grid>

    </Page>

元のスニペットのクラス名の最初の部分を、自分のアプリの名前空間に置き換える必要があります。 たとえば、作成したプロジェクトの名前が LightingCS だとすると、x:Class="App1.MainPage"x:Class="LightingCS.MainPage" に置き換えます。 また、xmlns:local="using:App1"xmlns:local="using:LightingCS" に置き換える必要があります。

  • アプリをビルド、デプロイ、および実行するには、F5 キーを押すか、[デバッグ]>[デバッグの開始] の順に選択します。

アプリを実行した後、センサーに当てる光を変更するか、エミュレーター ツールを使うことによって、光センサーの値を変更できます。

  • アプリを停止するには、Visual Studio に戻り、Shift キーを押しながら F5 キーを押すか、[デバッグ]>[デバッグの停止] の順にクリックします。

説明

上に示した例では、ごく短いコードを作成するだけで、光センサー入力をアプリに組み込むことができることがわかります。

このアプリでは、BlankPage メソッドで、既定のセンサーとの接続を確立しています。

_lightsensor = LightSensor.GetDefault(); // Get the default light sensor object

このアプリでは、BlankPage メソッドで、レポート間隔を設定しています。 次のコードは、デバイスでサポートされる最小の間隔を取得し、要求される 16 ミリ秒の間隔 (約 60 Hz のリフレッシュ レート) と比較します。 サポートされる最小の間隔が要求される間隔よりも大きい場合は、値を最小値に設定します。 それ以外の場合は、値を要求される間隔に設定します。

uint minReportInterval = _lightsensor.MinimumReportInterval;
uint reportInterval = minReportInterval > 16 ? minReportInterval : 16;
_lightsensor.ReportInterval = reportInterval;

ReadingChanged メソッドで、新しい光センサー データをキャプチャしています。 センサーのドライバーは、センサーから新しいデータを受け取るたびに、このイベント ハンドラーを使ってアプリに値を渡します。 このアプリの場合、このイベント ハンドラーが次の行で登録されています。

_lightsensor.ReadingChanged += new TypedEventHandler<LightSensor,
LightSensorReadingChangedEventArgs>(ReadingChanged);

プロジェクトの XAML 内にある TextBlock に、以下の新しい値が書き込まれます。

<TextBlock HorizontalAlignment="Left" Height="44" Margin="52,38,0,0" TextWrapping="Wrap" Text="LUX Reading" VerticalAlignment="Top" Width="150"/>
 <TextBlock x:Name="txtLuxValue" HorizontalAlignment="Left" Height="44" Margin="224,38,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="217"/>