Created
June 19, 2015 18:32
-
-
Save r0adkll/fa84d23a41d4b250f2fa to your computer and use it in GitHub Desktop.
Get cached battery level
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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