Tags

, , , ,

Here is the code implementation that shows device battery percentage in Toast. On Android battery level can be quaried using IntentFilter and Context.RegisterReceiver()

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

namespace BatteryPerc
{
	[Activity (Label = "Battery Percentage", MainLauncher = true, Icon = "@drawable/icon")]
	public class MainActivity : Activity
	{

		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);

			// Set our view from the "main" layout resource
			SetContentView (Resource.Layout.Main);

			// Get our button from the layout resource,
			// and attach an event to it
			Button button = FindViewById<Button> (Resource.Id.myButton);

			button.Click += delegate {
				var filter  = new IntentFilter(Intent.ActionBatteryChanged);
				var battery = RegisterReceiver(null, filter);
				int level   = battery.GetIntExtra(BatteryManager.ExtraLevel, -1);
				int scale   = battery.GetIntExtra(BatteryManager.ExtraScale, -1);

				int BPercetage = (int)System.Math.Floor (level * 100D / scale);
				Toast.MakeText(this,BPercetage.ToString(),ToastLength.Long).Show();
			};
		}
	}
}

I hope this will help 🙂 Happy coding 🙂

Advertisements