r0adkll
6/19/2015 - 6:32 PM

Get cached battery level

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;
	}