Monitoring the Battery Status in Android Programmatically

Attachments

File Description File size Downloads
Battery-Monitor.apk Download and start monitoring Battery State on your Android device.
2 MB 187

How can I get battery information and charging status etc. on my Android device or should I download the available app from play store to monitoring the battery status this type of question arises in your mind. But if you know how to write the code snippet for android why can’t you make your own app that monitors the battery of your own android device. Let’s see how.

In this tutorial, we’ll learn how to get all the details or information of battery such as Battery percentage/level, Battery Health, Battery Temperature, Charging Source/Type (USB, AC Charger, Wireless Charger), Charging Status (Charging/Discharging), Technology used in Battery and Voltage. So below is the complete step by step tutorial for monitoring the battery status in android programmatically.

download Source code

Creating Android Project:

Refer Android beginners app development guide if you are a beginner or if you don’t know how to create a project in the android studio.

1. Create a new project in Android Studio from File ⇒ New Project and fill the project details.

2. Open build.gradle (app/build.gradle) and set  the minSdkVersion and targetSdkVersion to 22 or higher, and also don’t forget to include these dependencies in your app gradle.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.gadgetcreek.battery_monitoring"
        minSdkVersion 10
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.1'
    compile 'com.android.support:cardview-v7:25.1.1'
    testCompile 'junit:junit:4.12'
}

3. Open the layout file for main activity(activity_main.xml) located under src/main/res/layout/activity_main.xml and add the below layout code.

<?xml version="1.0" encoding="utf-8"?>
    <android.support.v7.widget.CardView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        tools:context="com.gadgetcreek.battery_monitoring.MainActivity"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_margin="5dp"
        card_view:cardCornerRadius="8dp"
        card_view:contentPadding="10dp"
        card_view:cardBackgroundColor="@android:color/white">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="18sp"
                android:textColor="@android:color/black"
                android:text="@string/app_desc" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:layout_marginTop="20dp"
                    android:layout_marginBottom="20dp">

                    <ImageView
                        android:id="@+id/battery"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:src="@mipmap/battery_icon"
                        />

                    <TextView
                        android:id="@+id/battey_percentage"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textSize="19sp"
                        android:textStyle="bold"
                        android:layout_marginStart="10dp"
                        android:layout_marginLeft="10dp"
                        android:textColor="@color/colorPrimary"/>

                </LinearLayout>

            <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scrollbars="none">

                <LinearLayout
                     android:layout_width="match_parent"
                     android:layout_height="wrap_content"
                     android:orientation="horizontal"
                     android:layout_margin="10dp">

                    <TextView
                        android:id="@+id/textView1"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textSize="16sp"
                        android:textColor="@android:color/black"/>

                    <TextView
                        android:id="@+id/textView2"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:textSize="16sp"
                        android:layout_gravity="end"
                        android:gravity="end"
                        android:textColor="@color/colorAccent"/>

                </LinearLayout>

            </ScrollView>

        </LinearLayout>

    </android.support.v7.widget.CardView>

Following is the content of the res/values/strings.xml.

<resources>
    <string name="app_name">Battery-Monitoring</string>
    <string name="app_desc">Please connect your device to a power source.
        The charging status should show as charging.
        Check your battery condition and observe if the charging percentage changes over time.</string>
</resources>

4. For determining the current charge status and battery properties. The BatteryManager broadcasts all battery and charging details in a sticky Intent that includes the charging status. Then register a BroadcastReceiver—by simply calling registerReceiver passing in mBroadcastReceiver as the receiver as shown in the next snippet, the current battery status intent is returned.

IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Context.registerReceiver(mBroadcastReceiver,iFilter);

The BatteryManager broadcasts an action whenever the device is connected or disconnected from power. It’s important to receive these events even while your app isn’t running and alter your refresh rate accordingly. To extarct both the current charging status and, if the device is being charged also check how we are charging whether it’s charging via USB, AC Charger or Wireless. we have to maximize the rate of your background updates in the case where the device is connected to an AC charger, reduce the rate if the charge is over USB, and lower it further if the battery is discharging.

int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);

            if(chargePlug == BatteryManager.BATTERY_PLUGGED_USB)
            {
                power_source = "USB";
            }
            if(chargePlug == BatteryManager.BATTERY_PLUGGED_AC)
            {
                power_source = "AC Adapter";
            }
            if(chargePlug == BatteryManager.BATTERY_PLUGGED_WIRELESS)
            {
                power_source = "Wireless";
            }

If you want to perform transformation while your device is charging eg: Blink battery icon and stop while its discharging, so create an blink.xml file which defines type of animation to perform and place the animation XML file under the res/anim/ directory of your Android project. If you don’t have anim folder in your res directory create one. Following is snippet of simple Blink animation.

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

  <alpha
      android:duration="1000"
      android:fromAlpha="0.0"
      android:interpolator="@android:anim/accelerate_interpolator"
      android:repeatCount="infinite"
      android:toAlpha="1.0" />

</set>

Next in your Activity create an object of Animation class. And load the xml animation using AnimationUtils by calling loadAnimation function.  You can start animation whenever you want by calling startAnimation on any UI element and stop animation by calling clearAnimation. In this example i am calling blink animation on ImageView.

Animation animationBlink = AnimationUtils.loadAnimation(this, R.anim.blink);

// Get the status of battery Eg. Charging/Discharging
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
if(status == BatteryManager.BATTERY_STATUS_CHARGING)
{
image.startAnimation(animationBlink);
}
if(status == BatteryManager.BATTERY_STATUS_DISCHARGING)
{
image.clearAnimation();
}

Follow below MainActivity Code for more detail.

5. Now Open the MainActivity.java file located under src/main/Java/MainActivity.java and add below code.

package com.gadgetcreek.battery_monitoring;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    Context Context;
    TextView textView1,textView2,battery_percentage;
    ImageView image;
    Animation animationBlink;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        animationBlink = AnimationUtils.loadAnimation(this, R.anim.blink);

        image = (ImageView)findViewById(R.id.battery);

        // Get the application context
        Context = getApplicationContext();

        // Initialize a new IntentFilter instance
        IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);

        // Register the broadcast receiver
        Context.registerReceiver(mBroadcastReceiver,iFilter);

        // Get the widgets reference from XML main
        battery_percentage = (TextView) findViewById(R.id.battey_percentage);
        textView1 = (TextView) findViewById(R.id.textView1);
        textView2 = (TextView) findViewById(R.id.textView2);

    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            String charging_status="",battery_condition="",power_source="Unplugged";

            // Get the battery percentage
            int  level= intent.getIntExtra(BatteryManager.EXTRA_LEVEL,0);

            // Get the battery condition
            int  health= intent.getIntExtra(BatteryManager.EXTRA_HEALTH,0);

            if(health == BatteryManager.BATTERY_HEALTH_COLD)
            {
                battery_condition = "Cold";
            }
            if (health == BatteryManager.BATTERY_HEALTH_DEAD)
            {
                battery_condition = "Dead";
            }
            if (health == BatteryManager.BATTERY_HEALTH_GOOD)
            {
                battery_condition = "Good";
            }
            if (health == BatteryManager.BATTERY_HEALTH_OVERHEAT)
            {
                battery_condition = "Over Heat";
            }
            if (health == BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE)
            {
                battery_condition = "Over Voltage";
            }
            if(health == BatteryManager.BATTERY_HEALTH_UNKNOWN)
            {
                battery_condition = "Unknown";
            }
            if(health == BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE)
            {
                battery_condition = "Unspecified failure";
            }

            // Get the battery temperature in celcius
            int  temperature_c= (intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE,0))/10;

            //  Celsius to Fahrenheit battery temperature conversion
            int temperature_f = (int)(temperature_c*1.8+32);

            // Get the battery power source
            int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);

            if(chargePlug == BatteryManager.BATTERY_PLUGGED_USB)
            {
                power_source = "USB";
            }
            if(chargePlug == BatteryManager.BATTERY_PLUGGED_AC)
            {
                power_source = "AC Adapter";
            }
            if(chargePlug == BatteryManager.BATTERY_PLUGGED_WIRELESS)
            {
                power_source = "Wireless";
            }

            // Get the status of battery Eg. Charging/Discharging
            int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);

            if(status == BatteryManager.BATTERY_STATUS_CHARGING)
            {
                charging_status = "Charging";
                image.startAnimation(animationBlink);
            }

            if(status == BatteryManager.BATTERY_STATUS_DISCHARGING)
            {
                charging_status = "Not Charging";
                image.clearAnimation();
            }

            if (status == BatteryManager.BATTERY_STATUS_FULL)
            {
                charging_status = "Battery Full";
            }

            if(status == BatteryManager.BATTERY_STATUS_UNKNOWN)
            {
                charging_status = "Unknown";
            }

            if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING)
            {
                charging_status = "Not Charging";
            }

            // Get the battery technology
            String  technology= intent.getExtras().getString(BatteryManager.EXTRA_TECHNOLOGY);

            // Get the battery voltage
            int  voltage= intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE,0);

            //Display the output of battery Status
            battery_percentage.setText("Battery Percentage: "+level+"%");

            textView1.setText("Battery Condition:\n\n"+
                              "Battery Temperature:\n\n"+
                              "Power Source:\n\n"+
                              "Charging Status:\n\n"+
                              "Battery Type:\n\n"+
                              "Voltage:");

            textView2.setText(battery_condition+"\n\n"+
                              temperature_c+" "+ (char) 0x00B0 +"C / "+ temperature_f +" "+ (char) 0x00B0 +"F\n\n"+
                              power_source+"\n\n"+
                              charging_status+"\n\n"+
                              technology+"\n\n"+
                              voltage+"mV"

            );

        }
    };

}

With this, we have completed coding work on Monitoring the Battery State in Android Programmatically. To run the app from Android studio, click Run icon Eclipse Run Icon from the toolbar.

2 thoughts on “Monitoring the Battery Status in Android Programmatically”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.