Have you ever built an Android app that’s supposed to run like a marathon champ, only to find it napping halfway through the race? If you’ve been working with foreground services that need to hum along for a long time—say, chatting with a server or crunching some critical tasks—you’ve probably run into Android’s battery-saving antics. Since Android M (API 23, a.k.a. Marshmallow), Google rolled out Doze and App Standby modes to keep devices sipping power instead of guzzling it. Great for battery life, sure, but a total buzzkill for apps that need to stay awake when the screen’s off or the device is locked.

Picture this: your app’s foreground service is diligently trying to sync data, but Android decides it’s bedtime. Into standby mode it goes, leaving your service in the dust. Frustrating, right? But don’t worry—there’s a way to give your app a caffeine boost and keep it running strong. Enter the REQUEST_IGNORE_BATTERY_OPTIMIZATIONS permission—a nifty little trick to tell Android, “Hey, my app’s got work to do!” In this post, we’ll dive into how to use this programmatically (with Kotlin examples, of course), share some developer wisdom to keep you on the right track, and explore ways to ensure your app stays alive in the background. Plus, we’ll sprinkle in a bit of fun because who said coding can’t have a laugh or two?

REQUEST_IGNORE_BATTERY_OPTIMIZATIONS Dialog

The Problem: Doze and App Standby Crash the Party

Let’s set the scene. Back in Android 6.0, Google introduced two battery-saving features that changed the game:

  • Doze Mode: Kicks in when your device is sitting still and unused—think of it as Android tucking itself in for a nap. It delays background CPU and network tasks to save power.
  • App Standby: Targets apps you haven’t touched in a while, putting them on a timeout and restricting their resource access.

These are brilliant for keeping your phone alive longer, but they’re a nightmare if your app relies on a foreground service to keep running. Locked screen? Display off? Boom—your app’s in standby, and that server it was supposed to ping is left hanging. For businesses or use cases where constant operation is non-negotiable—like real-time tracking or messaging—this is a dealbreaker.

The Fix: Ignoring Battery Optimization Like a Pro

Thankfully, Android offers a lifeline: the REQUEST_IGNORE_BATTERY_OPTIMIZATIONS permission. This lets your app sidestep Doze and App Standby, keeping your foreground service chugging along even when the device wants to snooze. Let’s break down how to make this happen programmatically, with some shiny Kotlin code to light the way.

Step 1: Declare the Permission

First, you’ll need to add this line to your app’s AndroidManifest.xml. It’s like RSVPing to the “stay awake” party:

<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />Code language: HTML, XML (xml)

Step 2: Check and Request the Permission

Now, let’s write some code to check if your app’s already on the VIP list for ignoring battery optimizations. If it’s not, we’ll prompt the user to grant that golden ticket. Here’s how it looks in Kotlin:

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.PowerManager
import android.provider.Settings
import androidx.annotation.RequiresApi

@RequiresApi(Build.VERSION_CODES.M)
fun ignoreBatteryOptimization(context: Context) {
    val packageName = context.packageName
    val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager
    if (!pm.isIgnoringBatteryOptimizations(packageName)) {
        val intent = Intent().apply {
            action = Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
            data = Uri.parse("package:$packageName")
        }
        context.startActivity(intent)
    }
}Code language: JavaScript (javascript)

What’s happening here? We grab the app’s package name and the PowerManager service to check if we’re already ignoring battery optimizations with isIgnoringBatteryOptimizations(). If not, we fire up an intent with ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, pointing it to our app’s package. This pops up a system dialog asking the user, “Hey, can this app stay awake?” Since this only works on Android M (API 23) and up, the @RequiresApi annotation keeps things safe.

When you call this function—say, from an activity or a button click—Android shows a friendly dialog. If the user says yes, your app gets a backstage pass to keep running. Easy, right?

Best Practices: Don’t Be That App

Before you go wild with this power, let’s talk responsibility. Ignoring battery optimization is like handing your app an all-night energy drink—it’s awesome, but you don’t want to overdo it. Here’s how to wield this tool like a seasoned dev:

  1. Only When Necessary: Don’t request this unless your app really needs it—think music players, fitness trackers, or server-syncing apps. If your app’s just chilling in the background for no reason, users won’t be happy when their battery’s toast by lunchtime.
  2. Be Transparent: Tell users why you’re asking. Pop up a quick dialog beforehand saying something like, “We need to stay awake to keep syncing your data—cool with you?” Clarity builds trust.
  3. Plan for Rejection: Users might say no, and that’s okay. Make sure your app doesn’t throw a tantrum—fall back to a lighter mode or notify them of limited features.
  4. Test Thoroughly: Run your app through comprehensive testing scenarios—screen off, device idle, Doze mode on. Confirm that your foreground service keeps humming without interruptions.
  5. Keep Battery in Check: Even with this permission, don’t let your app guzzle power like it’s at an all-you-can-eat buffet. Optimize your code to play nice with the device.

Think of it like this: you’re asking the user to trust you with their battery life. Don’t abuse that trust, or they’ll swipe you away faster than you can say “force stop.”

Keeping Your App Running in the Background

Ignoring battery optimization is a big win, but it’s not the whole story. To make sure your app stays alive and kicking in the background, you’ll need a few more tricks up your sleeve:

  1. Foreground Services: These are your bread and butter for long-running tasks. Set up a foreground service with a notification (Android requires it), and it’ll keep going strong. It’s like giving your app a megaphone to say, “I’m still here!”
  2. Wake Locks (Use Sparingly): Need the device to stay awake for a bit? Wake locks can help, but they’re battery vampires—use them only when essential and release them ASAP.
  3. Scheduled Jobs: For tasks that don’t need to run constantly, tools like WorkManager or AlarmManager can wake your app up at set times, even in the background.
  4. Smart Networking: If your app’s talking to a server, batch those requests and use efficient protocols. Less chatter means less battery drain.
  5. Keep Users in the Loop: Show a notification or status update so users know what’s happening. Nobody likes a silent app hogging resources in the shadows.

Combine these with your battery optimization bypass, and your app will be the Energizer Bunny of the Android world—keeps going and going.

The Fun Side: Dancing with Doze

Let’s be real—tackling battery optimization is like a tango with Android. It’s trying to save juice, and you’re pleading, “Just one more song!” It’s a playful tug-of-war that makes Android development such a wild ride. Sure, you could let your app run rampant, but where’s the finesse in that? Strike a balance, and you’ll have an app that’s both unstoppable and user-friendly. After all, nobody wants to be the app that gets uninstalled because it threw a party in the battery’s house without an invite.

Wrapping It Up

There you have it—your guide to programmatically ignoring battery optimization on Android. With the REQUEST_IGNORE_BATTERY_OPTIMIZATIONS permission and some Kotlin magic, you can keep your foreground services alive, even when Doze and App Standby try to crash the party. Follow the best practices, layer in some background-running strategies, and you’ll have an app that’s reliable without being a battery bully.

So go ahead, set your app free to do its thing in the background. Let it hum along happily while the device dreams of power-saving glory. You’ve got the tools—now make something awesome.

Happy coding!

https://androidboss.info/2025/03/24/doze-mode-android-developers-guide

0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments