Introduction
This article demonstrates how to check battery status using C# and XAML in Xamarin.Forms.
Step 1
Open Visual Studio and go to New Project >> Installed >> Visual C# >> Cross Platform.
Select Cross-Platform App, Then, give your project a Name and Location; click “OK”.
Step 2 After Project Creation, add the following NuGet Packages to your project.
Go to Solution Explorer and select your solution. Right-click the Dialogue Box, Open and Select “Manage NuGet Packages for Solution”.
Now, select the following NuGet Package and select your project to install the NuGet Package.
Step 2
Open Solution Explorer >> Project Name (Portable) >> MainPage.xaml. Double Click Open the Design View of this page. This page is DesignPage or Frontend.
The code is given below.
Xaml Code We are creating Button and Label inside the StackLayout. Assign the name as per your wish.
Step 4
Open Solution Explorer >> Project Name (Portable) >> MainPage.xaml.cs. Double-click to open the backend view of this page. This page is backend.
The code is given below.
C# Code We created the Button in Design Page, the Button click now results in the Battery Status. Button Name is BATTERY.
- public partial class MainPage : ContentPage
- {
- public MainPage()
- {
- InitializeComponent();
- }
-
- private void btn_Clicked(object sender, EventArgs e)
- {
- if (CrossBattery.IsSupported)
- {
- var falta = CrossBattery.Current.RemainingChargePercent;
- Lb1.Text = $"PERSENTAGE: {falta.ToString()}%\n";
-
- var status = CrossBattery.Current.Status;
- Lb1.Text += $"STATUS:{status.ToString()}\n";
-
- var source = CrossBattery.Current.PowerSource;
- Lb1.Text += $"MEDIUM: {source.ToString()}\n\n";
-
- CrossBattery.Current.BatteryChanged -=Current_BatteryChanged;
- CrossBattery.Current.BatteryChanged += Current_BatteryChanged;
- }
- }
-
- private void Current_BatteryChanged(object sender, Plugin.Battery.Abstractions.BatteryChangedEventArgs e)
- {
- LblStatus.Text = "STATUS NOW:" + e.Status.ToString()+"\n";
- LblStatus.Text += "BATTERY:" + e.IsLow.ToString();
- }
- }
Step 5
In this step, select Build & deploy option, followed by clicking "Start your application".
Now, go to the Run option, choose Debug. From the list of an Android Emulators or simulators, you can choose any API (Android Program Interface) Level Emulator and Simulator to run it.
Output
After a few seconds, you will see your app working.
When you connect your USB charger and click on the "BATTERY" button, this updates your application status.
Finally, we have successfully created an app for checking battery status in Xamarin.Forms.