Reacting to Power Levels

You can obtain the current battery level in your app, and, if the battery is low, you can then turn off nonessential features to preserve battery life. Here’s how.

1. In the helpers package, create a new class named Battery. In the constructor of the class, set the class name to a static string. Add two other static final integers: LOW_LEVEL (with the value 35) and CRITICAL_LEVEL (with the value 15). See Listing 9.22.

Listing 9.22 Creating the New Battery Class

public class Battery {    private static String CLASS_NAME;    private static final int LOW_LEVEL = 35;    private static final int CRITICAL_LEVEL = 15;    public Battery() {        CLASS_NAME = getClass().getName();    }}

2. Add ...

Get Learning Android™ Application Programming: A Hands-On Guide to Building Android Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.