Search code examples
androidbatterylevel

Show Battery current status and changed automatically on increase or decrease


I Build a android app in which i want to show the current battery status.I searched and i found the code for battery status but it will display battery status in text form like battery level remaining 50%.but i want to show it as indicator like below image.how can i do this. and i also want battery status automatically changed when its charging status increase or decrease.

code for battery status

package com.example.androidbatterypercentage;

  import android.os.BatteryManager;
  import android.os.Bundle;
  import android.app.Activity;
  import android.content.BroadcastReceiver;
  import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.view.Menu;
 import android.widget.TextView;

     public class MainActivity extends Activity {
   private TextView batteryPercent;
   private void getBatteryPercentage() {
    BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
         context.unregisterReceiver(this);
         int currentLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
         int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
         int level = -1;
         if (currentLevel >= 0 && scale > 0) {
             level = (currentLevel * 100) / scale;
          }
          batteryPercent.setText("Battery Level Remaining: " + level + "%");
      }
    };  
    IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
     registerReceiver(batteryLevelReceiver, batteryLevelFilter);
 }


     protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      batteryPercent = (TextView) this.findViewById(R.id.batteryLevel);
      getBatteryPercentage();
  }


  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
  }

  }

xml file is

    <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"
       tools:context=".MainActivity">


  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="@string/hello_world" />

  </RelativeLayout>

Solution

  • Hi there is the sample link for the current battery status.

    1) Display battery information of android device

    2) Get Device Battery Information

    You can used the process in thread,TimerTask or services to get automatically

    I hope this help