Skip to main content

android - Get battery level and percentage programmatically

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    android:background="#d5ebfa"
    >
    <ProgressBar
        android:id="@+id/pb"
        android:layout_width="150dp"
        android:layout_height="150dp"
        style="@android:style/Widget.ProgressBar.Horizontal"
        android:progressDrawable="@drawable/progressbar_states"
        android:layout_centerInParent="true"
        />
    <TextView
        android:id="@+id/tv_percentage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25dp"
        android:textColor="#000"
        android:layout_centerInParent="true"
        />
    <TextView
        android:id="@+id/tv_info"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        />
</RelativeLayout>
drawable/progressbar_states.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background">
        <shape
            android:shape="oval">
            <stroke
                android:width="5dp"
                android:color="#d0d4d7"
                />
            <solid android:color="#eef2f5"/>
        </shape>
    </item>
    <item android:id="@android:id/progress">
        <clip android:clipOrientation="vertical" android:gravity="bottom">
            <shape
                android:shape="oval">
                <stroke
                    android:width="5dp"
                    android:color="#ff0001"
                    />
                <gradient
                    android:startColor="#7fc97c"
                    android:endColor="#99f396"
                    android:centerColor="#89e386"
                    android:angle="270"
                    android:gradientRadius="50"
                    android:centerY=".50"
                    />
            </shape>
        </clip>
    </item>
</layer-list>
MainActivity.java

package com.cfsuman.me.androidcode;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;
import android.widget.ProgressBar;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {
    private Context mContext;

    private TextView mTextViewInfo;
    private TextView mTextViewPercentage;
    private ProgressBar mProgressBar;

    private int mProgressStatus = 0;

    /*
        BroadcastReceiver
            Base class for code that will receive intents sent by sendBroadcast().

            You can either dynamically register an instance of this class with
            Context.registerReceiver() or statically publish an implementation through
            the <receiver> tag in your AndroidManifest.xml.
    */
    // Initialize a new BroadcastReceiver instance
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            /*
                BatteryManager
                    The BatteryManager class contains strings and constants used for values in the
                    ACTION_BATTERY_CHANGED Intent, and provides a method for querying battery
                    and charging properties.
            */
            /*
                public static final String EXTRA_SCALE
                    Extra for ACTION_BATTERY_CHANGED: integer containing the maximum battery level.
                    Constant Value: "scale"
            */
            // Get the battery scale
            int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE,-1);
            // Display the battery scale in TextView
            mTextViewInfo.setText("Battery Scale : " + scale);

            /*
                public static final String EXTRA_LEVEL
                    Extra for ACTION_BATTERY_CHANGED: integer field containing the current battery
                    level, from 0 to EXTRA_SCALE.

                    Constant Value: "level"
            */
            // get the battery level
            int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL,-1);
            // Display the battery level in TextView
            mTextViewInfo.setText(mTextViewInfo.getText() + "\nBattery Level : " + level);

            // Calculate the battery charged percentage
            float percentage = level/ (float) scale;
            // Update the progress bar to display current battery charged percentage
            mProgressStatus = (int)((percentage)*100);

            // Show the battery charged percentage text inside progress bar
            mTextViewPercentage.setText("" + mProgressStatus + "%");

            // Show the battery charged percentage in TextView
            mTextViewInfo.setText(mTextViewInfo.getText() +
                    "\nPercentage : "+ mProgressStatus + "%");

            // Display the battery charged percentage in progress bar
            mProgressBar.setProgress(mProgressStatus);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // Request window feature action bar
        requestWindowFeature(Window.FEATURE_ACTION_BAR);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

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

        /*
            IntentFilter
                Structured description of Intent values to be matched. An IntentFilter can match
                against actions, categories, and data (either via its type, scheme, and/or path) in
                an Intent. It also includes a "priority" value which is used to order multiple
                matching filters.

                IntentFilter objects are often created in XML as part of a package's
                AndroidManifest.xml file, using intent-filter tags.
        */
        /*
            public IntentFilter (String action)
                New IntentFilter that matches a single action with no data. If no data
                characteristics are subsequently specified, then the filter will only match intents
                that contain no data.

            Parameters
                action : The action to match, i.e. Intent.ACTION_MAIN.
        */
        // Initialize a new IntentFilter instance
        IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);

        /*
            public abstract Intent registerReceiver (BroadcastReceiver receiver, IntentFilter filter)
                Register a BroadcastReceiver to be run in the main activity thread. The receiver will
                be called with any broadcast Intent that matches filter, in the main application thread.

                The system may broadcast Intents that are "sticky" -- these stay around after the
                broadcast as finished, to be sent to any later registrations. If your IntentFilter
                matches one of these sticky Intents, that Intent will be returned by this function
                and sent to your receiver as if it had just been broadcast.

        Parameters
            receiver : The BroadcastReceiver to handle the broadcast.
            filter : Selects the Intent broadcasts to be received.
        Returns
            The first sticky intent found that matches filter, or null if there are none.
        */
        // Register the broadcast receiver
        mContext.registerReceiver(mBroadcastReceiver,iFilter);

        // Get the widgets reference from XML layout
        mTextViewInfo = (TextView) findViewById(R.id.tv_info);
        mTextViewPercentage = (TextView) findViewById(R.id.tv_percentage);
        mProgressBar = (ProgressBar) findViewById(R.id.pb);
    }
}
More android examples

Popular posts from this blog

How to use NumberPicker in Android

Table of contentsNumberPicker ExamplesetOnValueChangedListeneronValueChange()setWrapSelectorWheel()setMinValue()setMinValue()setMaxValue()NumberPicker with String ArraysetDisplayedValues()String Array1. NumberPicker Example activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/rl" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" tools:context=".MainActivity" android:background="#ffffff" > <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="25dp" android:text="Select a number..." /> <NumberPicker android:id="@+id/np" …

TextView new line (multiline) in android

TextView new line (multiline) TextView display text on android app. by default, TextView show text on a single line, and if it is long then TextView take more lines to display its text. android developers can generate a new line on TextView both programmatically and syntactically. android developers can make a multiline TextView without splitting text to multiline by android:minLines attribute.

the following android example code demonstrate us how can we syntactically create a new line on TextView widget by xml layout file and string resource file.

the simplest way to create a new line on TextView is android:text attribute. android:text attribute allow us to display text on android app. we can add a simple '\n' to TextView text where we want to start a new line. in this way we can create a multiline TextView widget in android app. we can assign android:text attribute value by this way android:text="Line1 \n Line2 \n Line3" for a TextView widget. this value will…

How to change TextView font size in android

TextView font size TextView widget display text on android application. we can set or change TextView font size statically by declarative syntax in xml layout file or programmatically at run time in java file. even we can use an xml file source to define font size.

the following example code demonstrate us how can we define TextView font size in xml layout file and how can we uses dimens.xml to reference font size. in this example we did not changes any coding in java file, so here we only include the layout xml file and dimens.xml file. activity_main.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:layout_margin="25dp" tools:context=".MainActivity" > <TextView android:id=&…