Book Image

iOS Development with Xamarin Cookbook

By : Dimitrios Tavlikos (USD)
Book Image

iOS Development with Xamarin Cookbook

By: Dimitrios Tavlikos (USD)

Overview of this book

Table of Contents (22 chapters)
iOS Development with Xamarin Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Retrieving the battery information


In this recipe, we will learn how to read the charging states of the device and its battery usage.

Getting ready

Create a new Single View Application in Xamarin Studio and name it BatteryInfoApp.

How to do it...

Perform the following steps:

  1. Add a label to the view of the controller.

  2. Override the ViewWillAppear method in the controller class as follows:

    private NSObject batteryStateChangeObserver;
    public override void ViewWillAppear (bool animated)
    {
      base.ViewWillAppear (animated);
      UIDevice.CurrentDevice.BatteryMonitoringEnabled = true;
      this.batteryStateChangeObserver = UIDevice.Notifications.ObserveBatteryStateDidChange((s, e) => {
        this.lblOutput.Text = string.Format("Battery level: {0}", UIDevice.CurrentDevice.BatteryLevel);
        Console.WriteLine("Battery state: {0}", UIDevice.CurrentDevice.BatteryState);
      });
    }
  3. Compile and run the app on the device. After the app loads, disconnect and/or connect the USB cable of the device. The battery level will...