Skip to content

Instantly share code, notes, and snippets.

@findjigar
Created February 26, 2020 03:30
Show Gist options
  • Save findjigar/09b5d4df22bbbfce684c2069d2c593eb to your computer and use it in GitHub Desktop.
Save findjigar/09b5d4df22bbbfce684c2069d2c593eb to your computer and use it in GitHub Desktop.
Useful extension functions for Andorid
/**
* Extension function on [Context] to get current battery level
*/
fun Context.getBatteryLevel(): Float? {
val batteryStatus: Intent? = registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
batteryStatus?.let { intent ->
val level: Int = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
val scale: Int = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
return level * 100 / scale.toFloat()
}
return null
}
/**
* Check whether power saving mode is enabled or not
*/
fun Context.isPowerSaveModeEnabled(): Boolean {
(getSystemService() as PowerManager?)?.let {
return it.isPowerSaveMode
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment