728x90
728x170

디바이스 데이터를 가져오거나 디바이스 센서 등 디바이스에 관련한 내용을 정리했습니다.

doc 는 일부 코드만 있는데 하나의 프로젝트로 만들었습니다.

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="Maui.BasicApp.MainPage"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">

    <ScrollView>
        <VerticalStackLayout
            Padding="30,0"
            Spacing="25"
            VerticalOptions="Center">

            <HorizontalStackLayout>
                <Label Text="Always On Screen" VerticalTextAlignment="Center" />

                <Switch
                    x:Name="AlwaysOnSwitch"
                    IsToggled="False"
                    Toggled="AlwaysOnSwitch_Toggled" />
            </HorizontalStackLayout>

            <Label x:Name="DisplayDeviceLabel" />

            <Label x:Name="DisplayDetailsLabel" />

            <Label x:Name="BatteryStateLabel" />
            <Label x:Name="BatteryLevelLabel" />

            <HorizontalStackLayout>
                <Button
                    x:Name="HapticShortButton"
                    Margin="5"
                    Clicked="HapticShortButton_Clicked"
                    HorizontalOptions="Center"
                    Text="Haptic Short" />

                <Button
                    x:Name="HapticLongButton"
                    Margin="5"
                    Clicked="HapticLongButton_Clicked"
                    HorizontalOptions="Center"
                    Text="Haptic Long" />
            </HorizontalStackLayout>

            <HorizontalStackLayout>
                <Button
                    x:Name="VibrateStartButton"
                    Margin="5"
                    Clicked="VibrateStartButton_Clicked"
                    HorizontalOptions="Center"
                    Text="Vibrate Start" />

                <Button
                    x:Name="VibrateStoputton"
                    Margin="5"
                    Clicked="VibrateStopButton_Clicked"
                    HorizontalOptions="Center"
                    Text="Vibrate Stop" />
            </HorizontalStackLayout>

            <HorizontalStackLayout>
                <Label Text="Flash" VerticalTextAlignment="Center" />
                <Switch
                    x:Name="FlashlightSwitch"
                    IsToggled="False"
                    Toggled="FlashlightSwitch_Toggled" />
            </HorizontalStackLayout>

        </VerticalStackLayout>

    </ScrollView>
</ContentPage>

MainPage.xaml.cs

namespace Maui.BasicApp;

public partial class MainPage : ContentPage
{
    int count = 0;

    public MainPage()
    {
        InitializeComponent();

        ReadDeviceInfo();

        ReadDeviceDisplay();

        WatchBattery();
    }

    /// <summary>
    /// 디바이스 정보 가져오기
    /// </summary>
    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();
    }

    /// <summary>
    /// 디스플레이 정보 가져오기
    /// </summary>
    private void ReadDeviceDisplay()
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        sb.AppendLine($"Pixel width: {DeviceDisplay.Current.MainDisplayInfo.Width} / Pixel Height: {DeviceDisplay.Current.MainDisplayInfo.Height}");
        sb.AppendLine($"Density: {DeviceDisplay.Current.MainDisplayInfo.Density}");
        sb.AppendLine($"Orientation: {DeviceDisplay.Current.MainDisplayInfo.Orientation}");
        sb.AppendLine($"Rotation: {DeviceDisplay.Current.MainDisplayInfo.Rotation}");
        sb.AppendLine($"Refresh Rate: {DeviceDisplay.Current.MainDisplayInfo.RefreshRate}");

        DisplayDetailsLabel.Text = sb.ToString();
    }

    /// <summary>
    /// 배터리 정보 가져오기
    /// </summary>
    private void WatchBattery()
    {
        Battery.Default.BatteryInfoChanged += Battery_BatteryInfoChanged;
    }

    /// <summary>
    /// 배터리 상태 변경시 발생 이벤트
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void Battery_BatteryInfoChanged(object sender, BatteryInfoChangedEventArgs e)
    {
        BatteryStateLabel.Text = e.State switch
        {
            BatteryState.Charging => "Battery is currently charging",
            BatteryState.Discharging => "Charger is not connected and the battery is discharging",
            BatteryState.Full => "Battery is full",
            BatteryState.NotCharging => "The battery isn't charging.",
            BatteryState.NotPresent => "Battery is not available.",
            BatteryState.Unknown => "Battery is unknown",
            _ => "Battery is unknown"
        };

        BatteryLevelLabel.Text = $"Battery is {e.ChargeLevel * 100}% charged.";
    }

    /// <summary>
    /// 슬립모드 빠질지 여부
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void AlwaysOnSwitch_Toggled(object sender, ToggledEventArgs e)
    {
        DeviceDisplay.Current.KeepScreenOn = AlwaysOnSwitch.IsToggled;
    }

    /// <summary>
    /// 짧은 Haptic
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void HapticShortButton_Clicked(object sender, EventArgs e)
    {
        HapticFeedback.Default.Perform(HapticFeedbackType.Click);
    }

    /// <summary>
    /// 긴 Haptic
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void HapticLongButton_Clicked(object sender, EventArgs e)
    {
        HapticFeedback.Default.Perform(HapticFeedbackType.LongPress);
    }

    /// <summary>
    /// 진동 발생
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void VibrateStartButton_Clicked(object sender, EventArgs e)
    {
        // 5 초마다 진동
        Vibration.Default.Vibrate(TimeSpan.FromSeconds(5));
    }

    /// <summary>
    /// 진동 취소
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void VibrateStopButton_Clicked(object sender, EventArgs e)
    {
        Vibration.Default.Cancel();
    }

    /// <summary>
    /// 플래시 켜고 끄기
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private async void FlashlightSwitch_Toggled(object sender, ToggledEventArgs e)
    {
        try
        {
            if (FlashlightSwitch.IsToggled)
            {
                await Flashlight.Default.TurnOnAsync();
            }
            else
            {
                await Flashlight.Default.TurnOffAsync();
            }
        }
        catch (FeatureNotSupportedException ex)
        {
            // Handle not supported on device exception
        }
        catch (PermissionException ex)
        {
            // Handle permission exception
        }
        catch (Exception ex)
        {
            // Unable to turn on/off flashlight
        }
    }
}

 

결과

[Source]

https://github.com/kei-soft/Maui.BasicApp

 

GitHub - kei-soft/Maui.BasicApp

Contribute to kei-soft/Maui.BasicApp development by creating an account on GitHub.

github.com

 

728x90
그리드형
Posted by kjun
,