Skip to content

Instantly share code, notes, and snippets.

@r0adkll
Created June 19, 2015 18:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save r0adkll/fa84d23a41d4b250f2fa to your computer and use it in GitHub Desktop.
Save r0adkll/fa84d23a41d4b250f2fa to your computer and use it in GitHub Desktop.
Get cached battery level
private static float mCurrentBatteryPct;
private static long mCurrentBatteryPctDateMs;
/**
* A flavor of {@link #getCurrentBatteryLevel(Context)} that only polls the battery level from the OS
* every once in a while in an attempt to limit battery drain vs battery data freshness.
*
* @param readingPeriodMs the reading period (ms)
* @return the current battery level(%)
*/
public static float getCachedOrCurrentBatteryLevel(Context ctx, long readingPeriodMs){
final long currentTimeMs = System.currentTimeMillis();
if (currentTimeMs - mCurrentBatteryPctDateMs >= readingPeriodMs) {
Timber.d("getCachedOrCurrentBatteryLevel: battery level value has expired, polling a new one... ");
mCurrentBatteryPct = getCurrentBatteryLevel(ctx);
mCurrentBatteryPctDateMs = currentTimeMs;
}
return mCurrentBatteryPct;
}
/**
* Get the current Battery level in percentages
* @return the current battery level(%)
*/
public static float getCurrentBatteryLevel(Context ctx){
// Create Intent to reference Android's Sticky Batter intent (does not require a receiver)
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent battery = ctx.registerReceiver(null, ifilter);
// Get the Level and Scale from the intent
int level = battery.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = battery.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
// Calculate the percentage
float batteryPct = level / (float)scale;
return batteryPct;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment