Methods for accessing battery status on an android device

Hi,
How is the battery status on an android device accessed?

Any help is much appreciated.

Cheers.

Hi,
update: It looks like there are code examples using battery manager method from ‘android.os.BatteryManager’ at the developer.android.com website however i also found that if i use the ADB shell and go to the power_supply/battery directory i can get access to lots of battery information:

adb shell
cactus:/ $ cd /sys/class/power_supply/battery
cactus:/sys/class/power_supply/battery $ cat uevent
POWER_SUPPLY_NAME=battery
POWER_SUPPLY_STATUS=Charging
POWER_SUPPLY_HEALTH=Good
POWER_SUPPLY_PRESENT=1
POWER_SUPPLY_TECHNOLOGY=Li-poly
POWER_SUPPLY_CYCLE_COUNT=88
POWER_SUPPLY_CAPACITY=75
POWER_SUPPLY_CURRENT_NOW=401800
POWER_SUPPLY_CURRENT_AVG=324000
POWER_SUPPLY_VOLTAGE_NOW=4192000
POWER_SUPPLY_CHARGE_FULL=2765
POWER_SUPPLY_CHARGE_COUNTER=2073
POWER_SUPPLY_CHARGE_FULL_DESIGN=3000
POWER_SUPPLY_TEMP=180
POWER_SUPPLY_THERMAL_CONTROL_LIMIT=-1,-1
POWER_SUPPLY_INPUT_CURRENT_NOW=500000
POWER_SUPPLY_VOLTAGE_MAX=4400000
POWER_SUPPLY_CONSTANT_CHARGE_CURRENT_MAX=1100000

So i suppose the question is; is there a way to access this information from within processing script/java code?

Any help is much appreciated.

Cheers.

I’ve almost got it working, this should give you the percentage, you’ll have to rearrange the class yourself to extends functionality.

import android.R;
import android.app.Activity;
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.widget.TextView;

import android.content.Intent;
import android.app.Activity;
import android.content.Context;

import android.R;
import android.app.Activity;
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.widget.TextView;

Activity act;
Context ctx;
Battp bp;

int level;
void setup() {
  act = this.getActivity();
  ctx = act.getApplicationContext();
  bp = new Battp();
};

void draw() {
};

void mousePressed() {
  println(getBatteryCapacity(ctx));
  //println((batLevel));
};

public class Battp extends Activity {
  float batteryPercentage,batteryCapacity;

  Battp() {
    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus = act.registerReceiver(null, ifilter);
    level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    getBatteryCapacity(ctx);
    double currentCapacity = (level * getBatteryCapacity(ctx)) / 100;
    println("level", level);
    println("cc", currentCapacity);
  };

  public double getBatteryCapacity(Context context) {
    Object mPowerProfile;
    double batteryCapacity = 0;
    final String POWER_PROFILE_CLASS = "com.android.internal.os.PowerProfile";

    try {
      mPowerProfile = Class.forName(POWER_PROFILE_CLASS)
        .getConstructor(Context.class)
        .newInstance(context);

      batteryCapacity = (double) Class
        .forName(POWER_PROFILE_CLASS)
        .getMethod("getBatteryCapacity")
        .invoke(mPowerProfile);
    } 
    catch (Exception e) {
      e.printStackTrace();
    }
    return batteryCapacity;
  };
  //return level;
};

Hi,
And thanks for the reply and also thanks for your efforts on this, much appreciated.

I tried you code and unfortunately it failed with the following error related to the getBatteryCapacity() method:

> Task :app:compileDebugJavaWithJavac FAILED
----------
1. ERROR in /tmp/android1857772923646380959sketch/app/src/main/java/processing/test/andbatcapacity_v2/AndBatCapacity_V2.java (at line 55)
	println(getBatteryCapacity(ctx));
	        ^^^^^^^^^^^^^^^^^^
The method getBatteryCapacity(Context) is undefined

Unfortunately my programming skills are not good enough to know what this means.

Any help with this is much appreciated.

Cheers.

Woops that line should have been commented or removed, it should work.

HI,
And thanks for the reply.

OK i took out that line and tried again and this time it compiled but when the app started it crashed with the following error:

BUILD SUCCESSFUL in 10s
25 actionable tasks: 25 executed
FATAL EXCEPTION: Animation Thread
Process: processing.test.andbatcapacity_v2, PID: 13334
java.lang.RuntimeException: Can't create handler inside thread Thread[Animation Thread,5,main] that has not called Looper.prepare()
	at android.os.Handler.<init>(Handler.java:207)
	at android.os.Handler.<init>(Handler.java:119)
	at android.app.Activity.<init>(Activity.java:881)
	at processing.test.andbatcapacity_v2.AndBatCapacity_V2$Battp.<init>(AndBatCapacity_V2.java:63)
	at processing.test.andbatcapacity_v2.AndBatCapacity_V2.setup(AndBatCapacity_V2.java:48)
	at processing.core.PApplet.handleDraw(PApplet.java:1878)
	at processing.core.PSurfaceNone.callDraw(PSurfaceNone.java:478)
	at processing.core.PSurfaceNone$AnimationThread.run(PSurfaceNone.java:518)

Although i don’t think this error is related to the code?

Any help is much appreciated.

Cheers.

Are you using apde or processing android mode? I tested on processing android mode and it compiled fine.

Might need to check battery permissions.

@paulgoux === i think that your code cannot work, either in APDE or P5: the line which fires the first error is right: that method is defined for the another outer class & it means nothing in the fragment where you are calling it; then the other error is that you have to create an handler in the second class (extending activity- why???) and so have to use Looper.prepare(). Then i cannot understand your imports: why a textView eg? - Can you code for P5, with the fragment where you are?

Uhm deffo works ( only on processing android mode) later tested on apde which failed.

As for the rest I’m honestly not sure, android code is still very confusing for me. Its based on code I found on stackoverflow, I might be able to dig up the link later.

If you can help me understand fragments that would be amazing. I’ve tried making sense of the reference and certainly did not understand most of it.

import android.R;
import android.app.Activity;
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.widget.TextView;

import android.net.wifi.WifiManager;
import android.content.Intent;
import android.app.Activity;
import android.content.Context;

import android.R;
import android.app.Activity;
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.widget.TextView;

void setup() {
  getBattery_percentage();
};

void draw() {
};

void getBattery_percentage() {
  IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
  Intent batteryStatus = this.getActivity().getApplicationContext().registerReceiver(null, ifilter);
  int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
  int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
  float batteryPct = level / (float)scale;
  float p = batteryPct * 100;

  println("Battery percentage", String.valueOf(Math.round(p)));
}


Hi,
And thanks for the replies.

This updated code now works. I now just need to work on my understanding of how it all works.

Thank you both very much for your help with this.

Cheers.

1 Like

@paulgoux , @katesfb ===

this code can run but it is quite useless: i mean that you cannot get the message except in the setup; why? - Because the is not any broadcast receiver created, nor enregistered by code or Manifest; normally, if you want to know the battery state that is when the app is running, foreground or background and get an alery wether the battery level is too low. Your code register a receiver but it is “null” and you have to add also some pendingIntent.
For that you have to use the alarmManager class…

Im confused because i do not know enough about android code to know if there is a fault or not, but it does also work in draw.

@paulgoux === of course it can run onDraw && also with other events (mouseReleased…) but what i said is that you have not “permanent” listener for that, which is a broadcast receiver coupled with an alarm…

1 Like