Neste artigo veremos como obter o status da bateria do dispositivo em aplicações Xamarin.Forms.
As informações obtidas serão:
- RemainingChargePercent
Quantidade de carga da bateria em percentual. - Status
Status da bateria (Se está sendo carregada ou não) - PowerSource
Retorna um enum com o recurso de energia que está sendo usado pelo dispositivo, podendo ser: Battery, Ac, Usb, Wireless ou Other.
ADICIONANDO O NUGET PACKAGE
Clique com o botão direito em cima de sua Solution e selecione “Manage NuGet Packages for Solution…”.
Digite “Xam.Plugin.Battery” e selecione o plugin como demonstrado na imagem a seguir.
Selecione todos os projetos e clique no botão “Install”.
Xaml
Para visualizar as informações obtidas, crie 3 label’s, como demonstrado a seguir:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8" ?> | |
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" | |
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" | |
xmlns:local="clr-namespace:BatteryStatusDemo" | |
x:Class="BatteryStatusDemo.MainPage"> | |
<StackLayout VerticalOptions="Center" | |
HorizontalOptions="Center" > | |
<Label x:Name="RemainingChargePercent"/> | |
<Label x:Name="Status"/> | |
<Label x:Name="PowerSource"/> | |
</StackLayout> | |
</ContentPage> |
C#
Referencie o plugin Battery e utilize “CrossBattery.Current.” seguido da propriedade desejada, como demonstrado a seguir.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Plugin.Battery; | |
using Xamarin.Forms; | |
namespace BatteryStatusDemo | |
{ | |
public partial class MainPage : ContentPage | |
{ | |
public MainPage() | |
{ | |
InitializeComponent(); | |
RemainingChargePercent.Text = "RemainingChargePercent: " + CrossBattery.Current.RemainingChargePercent + " %"; | |
Status.Text = "Status: " + CrossBattery.Current.Status; | |
PowerSource.Text = "PowerSource: " + CrossBattery.Current.PowerSource; | |
} | |
} | |
} |
Resultado
Esse e todos os exemplos deste blog encontram-se disponíveis no GitHub.