bricklore bricklore - 1 year ago 58
Java Question

native app get batterylevel

I want to read the current battery level in a native app without using java.
The equivalent in Java would be:

BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
int scale = -1;
int level = -1;
int voltage = -1;
int temp = -1;
@Override
public void onReceive(Context context, Intent intent) {
level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);
voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);
Log.e("BatteryManager", "level is "+level+"/"+scale+", temp is "+temp+", voltage is "+voltage);
}
};

IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryReceiver, filter);


How is this possible by only using native code?

Answer Source

See this topic about dumpsys utility maybe run programmatically and read IO output buffer. I found few C++ sources you to look for. Running dumpsys may need root privileges.

Android ADB shell dumpsys tool

http://source.android.com/tech/input/dumpsys.html

http://code.metager.de/source/xref/android/4.1.1/frameworks/base/services/java/com/android/server/BatteryService.java

http://code.metager.de/source/xref/android/4.1.1/frameworks/native/cmds/dumpsys/dumpsys.cpp

http://code.metager.de/source/xref/android/4.1.1/frameworks/base/services/jni/com_android_server_BatteryService.cpp

http://code.metager.de/source/xref/android/4.1.1/frameworks/base/services/jni/onload.cpp

C++ sources, if Im right, reads /sys/class/power_supply virtual directory but what then happens someone may tell you more about the inner details of Linux system. Most of the code seems to be JNI interface stuff, updating private member fields in BatteryService.java class. OnLoad class registers jni<->java hooks but thats not what you need to know, just for reference here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download