The battery API is quite impressive, between other things not only can you get a battery’s voltage but you can also get the temperature, status and even an icon representing the current state of the battery.
In this post we’ll make an app that display’s all of the device’s battery information in a text view whenever there is a change of state in the battery.
The App’s Interface
Our interface will consists of a simple text view where we will show the battery’s information and an image view where we will display the battery’s current state using the image provided by the API to do this.
This is how the app will look.
the result: an app showing the device's battery information
Receiving Battery Updates
In order to receive the updated information from the battery we need to register a broadcast receiver and an intent filter. An intent filter tells the native battery app that our app is listening for its changes.
This is how we register a receiver with an intent filter:
this.registerReceiver(this.batteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
In the code above the receiver is an object we are going to make called batteryInfoReceiver, the intent filter is listening for the action battery changed.
Our receiver object is the following:
private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // this is where we deal with the data sent from the battery. } };
Battery Manager API
If you look at the battery manager api yo see that it has many constants that start with the word EXTRA_, these extras is the data we are able to get from the battery and also the type (int, String etc).
We can easily display the data in the views, the icon_small variable holds a resource id with the battery’s image:
This is the full Java code.
Battery Permissions
No special permissions are needed in the manifest file.
No comments: