Battery charge level. Xamarin forms

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

using Xamarin.Essentials;

namespace AppEssentials.Shared.Pages
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class BatteryStatusPage : ContentPage
    {
        public BatteryStatusPage()
        {
            InitializeComponent();
            SetBackground(Battery.ChargeLevel,
            Battery.State == BatteryState.Charging);

        }


        protected override void OnAppearing()
        {
            base.OnAppearing();
            Battery.BatteryInfoChanged += Battery_BatteryInfoChanged;
        }

        protected override void OnDisappearing()
        {
            base.OnDisappearing();
            Battery.BatteryInfoChanged -= Battery_BatteryInfoChanged;
        }

        void Battery_BatteryInfoChanged(object sender, BatteryInfoChangedEventArgs e)
        {
            SetBackground(e.ChargeLevel, e.State == BatteryState.Charging);
        }


        void SetBackground(double level, bool charging)
        {
            Color? color = null;

            var cLevel = "%" +(Battery.ChargeLevel * 100).ToString();

            var status = charging ? "Charging " + cLevel : "Not charging.. " + cLevel ;

            if(level > .5f)
            {
                color = Color.LightGreen.MultiplyAlpha(level);
            }
            else if(level > .1f)
            {
                color = Color.Yellow.MultiplyAlpha(1d - level);
            }
            else
            {
                color = Color.Red.MultiplyAlpha(1d - level);
            }

            BackgroundColor = color.Value;
            LabelBatteryLevel.Text = status;

        }

    }
}

**********************************************************
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="AppEssentials.Shared.Pages.BatteryStatusPage"
             Title="Battery Info">
    <ContentPage.Content>
        <StackLayout>
            <Label x:Name="LabelBatteryLevel"
                VerticalOptions="CenterAndExpand"
                HorizontalOptions="CenterAndExpand"
                TextColor="Black" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

Yorumlar