Skip to content

Instantly share code, notes, and snippets.

@neelratanguria
Created September 6, 2025 16:09
Show Gist options
  • Save neelratanguria/0f111fa952059ab2e0405eae05c4acfd to your computer and use it in GitHub Desktop.
Save neelratanguria/0f111fa952059ab2e0405eae05c4acfd to your computer and use it in GitHub Desktop.
val context = applicationContext
val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager
val isIgnoringBatteryOptimizations = pm.isIgnoringBatteryOptimizations(context.packageName)
if (isIgnoringBatteryOptimizations) {
// ✅ App is allowed to run without optimization ("Don't optimize" / "No restrictions")
} else {
// ⚠️ App is still restricted by battery optimization
try {
val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS).apply {
data = Uri.parse("package:" + applicationContext.packageName)
}
startActivity(intent)
} catch (e: Exception) {
e.printStackTrace()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment