In this article

Checking Battery Status

In this article

This article walks through the creation of an application that checks battery status. This article is based on the Battery Plugin by James Montemagno. For more information, see the GitHub repo.

Because Xamarin.Forms does not include functionality for checking the current battery status, this application will need to use DependencyService to take advantage of native APIs. This article will cover the following steps for using DependencyService:

When completed, the application using DependencyService will have the following structure:

Creating the Interface

First, create an interface in shared code that expresses the desired functionality. In the case of a battery checking application, the relevant information is the percentage of the battery remaining, whether the device is charging or not, and how the device is receiving power:

Coding against this interface in the shared code will allow the Xamarin.Forms app to access the power management APIs on each platform.

Note

Classes implementing the Interface must have a parameterless constructor to work with the DependencyService. Constructors can't be defined by interfaces.

iOS Implementation

The IBattery interface must be implemented in each platform-specific application project. The iOS implementation will use the native UIDevice APIs to access battery information. Note that the following class has a parameterless constructor so that the DependencyService can create new instances:

The [assembly] attribute above the namespace declaration registers the class as an implementation of the IBattery interface, which means that DependencyService.Get<IBattery> can be used in shared code to create an instance of it.

Implementing in Shared Code

Now that the interface has been implemented for each platform, the shared application can be written to take advantage of it. The application will consist of a page with a button that when tapped updates its text with the current battery status. It uses the DependencyService to get an instance of the IBattery interface. At runtime, this instance will be the platform-specific implementation that has full access to the native SDK.