Battery and network efficiency

Learn Android battery and network efficiency: Doze, App Standby buckets, WorkManager constraints, batching, avoiding wake locks, and OkHttp caching with HTTP/2. About 25 minutes.

Why it matters

  • A wake lock that is never released, or an alarm that fires every minute, keeps the CPU and radio awake. Android vitals in Play Console flags excessive partial wake locks, and users notice drain in the system battery screen.
  • Interviewers ask you to design a sync that survives Doze, App Standby buckets and metered networks without the user noticing stale data.
  • One shared OkHttpClient with a disk Cache reuses connections (HTTP/2 multiplexes many requests on one connection) and serves fresh cached responses without touching the network.
  • WorkManager constraints (setRequiredNetworkType, setRequiresCharging, setRequiresBatteryNotLow) are the recommended way to run deferrable background work. The system batches it with other apps' work instead of waking the device for you alone.

The simple explanation

  • Your phone is a house with a smart thermostat (the OS power manager).
  • Doze is night mode: the heating (CPU, network) is off, and the house only opens up briefly at set times (maintenance windows).
  • App Standby buckets are the thermostat knowing which rooms you use daily and which guest room you open once a month.
  • WorkManager is booking a repair visit for "when someone is home and the power is cheap" (constraints) instead of ringing the doorbell at 3 a.m.
  • A wake lock is you holding the thermostat dial: the house stays on until you let go.

How do you make an Android app battery and network efficient? Do as little background work as possible, batch what remains, and let the system schedule it. Concretely: run deferrable work through WorkManager with constraints, avoid holding your own wake locks, avoid frequent exact alarms, and send network requests through one cached OkHttpClient.

Doze (Android 6.0, API 23) starts when the device is unplugged, stationary and has the screen off for a while. In Doze the system suspends network access, ignores wake locks, defers standard AlarmManager alarms (including setExact()) to the next maintenance window, and does not run JobScheduler jobs or sync adapters. Maintenance windows open briefly and get further apart the longer the device stays idle. Android 7.0 added a lighter Doze phase that applies while the device is moving.

App Standby buckets (Android 9, API 28) rank each app by how recently and often the user uses it: active, working set, frequent, rare and restricted. The lower the bucket, the stricter the limits on jobs, alarms and (for rare) network access. The system assigns the bucket; you can read it with UsageStatsManager.getAppStandbyBucket().

MechanismWhat it limitsAPI to know
DozeNetwork, wake locks, alarms, jobs while idlePowerManager.isDeviceIdleMode()
App Standby bucketsJobs, alarms, network for rarely used appsUsageStatsManager.getAppStandbyBucket()
WorkManagerRuns deferrable work when constraints are metConstraints, PeriodicWorkRequestBuilder
OkHttp cacheRepeat downloads of the same responseCache(directory, maxSize)
HTTP/2Separate connections per requestNegotiated by OkHttp by default

WorkManager uses JobScheduler on API 23+, so its work also waits for maintenance windows and bucket quotas. Periodic work has a 15-minute minimum interval. Work you need soon after a user action can be marked expedited with setExpedited(); it is less affected by power limits but runs under a quota.

On the network side, every OkHttpClient owns its own connection pool and cache. Create one client for the app and share it. OkHttp negotiates HTTP/2 automatically with servers that support it, so many concurrent calls to one host share a single connection.

Notes

  • Doze suspends network, ignores wake locks and defers alarms and jobs until a maintenance window. setAlarmClock() still fires on time; setAndAllowWhileIdle() and setExactAndAllowWhileIdle() can fire during Doze but are rate-limited.
  • High-priority FCM messages are the supported way to wake an app in Doze for something the user must see. The app gets a short window of network access, and it should show a notification.
  • App Standby buckets are assigned by the system from user engagement. You cannot move your app to a better bucket; you can only design for the limits. Test with adb shell am set-standby-bucket <package> rare.
  • Test Doze with adb shell dumpsys battery unplug then adb shell dumpsys deviceidle force-idle; undo with adb shell dumpsys deviceidle unforce and adb shell dumpsys battery reset.
  • WorkManager constraints: setRequiredNetworkType(NetworkType.UNMETERED) for big downloads, CONNECTED for small syncs, setRequiresCharging(true) or setRequiresBatteryNotLow(true) for heavy work.
  • setRequiresDeviceIdle(true) means "the user has not used the device for a while" and suits heavy maintenance only. It can delay work a long time, and WorkManager throws IllegalArgumentException if you combine it with backoff criteria.
  • PeriodicWorkRequestBuilder enforces a 15-minute minimum interval. Use enqueueUniquePeriodicWork with ExistingPeriodicWorkPolicy.KEEP so repeated app starts do not schedule duplicates.
  • Wake locks are not deprecated, but you rarely need your own. WorkManager holds one for you while a worker runs. If you must hold one, use a timeout (acquire(timeoutMillis)) and release it in finally.
  • Exact alarms (setExact(), setExactAndAllowWhileIdle()) need the SCHEDULE_EXACT_ALARM permission on Android 12+, and on Android 14 it is not pre-granted to most newly installed apps. Use them only for user-facing, time-critical features like alarm clocks and calendar reminders.
  • ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS asks the user to exempt the app from Doze and App Standby. Google Play allows it only for apps whose core function breaks without it.
  • OkHttp only caches what HTTP caching headers allow. Cache-Control: no-store is never cached; max-age lets OkHttp serve the response without a request; ETag lets it revalidate with a cheap conditional request.
  • Batch and prefetch: one larger request every few minutes costs less energy than many small ones, because each request wakes the cellular radio, which then stays in a high-power state for a while.

Code example

This shows a production-style periodic sync: one app-wide OkHttp client with a disk cache, a CoroutineWorker that receives it through Hilt, and a schedule with network and battery constraints.

// NetworkModule.kt: one shared client for the whole app
import android.content.Context
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
import okhttp3.Cache
import okhttp3.OkHttpClient
import java.io.File
 
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
    @Provides
    @Singleton
    fun okHttpClient(@ApplicationContext context: Context): OkHttpClient =
        OkHttpClient.Builder()
            .cache(Cache(File(context.cacheDir, "http_cache"), 20L * 1024 * 1024))
            .build() // HTTP/2 is negotiated automatically when the server supports it
}
// SyncWorker.kt
import android.content.Context
import androidx.hilt.work.HiltWorker
import androidx.work.*
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.IOException
import java.util.concurrent.TimeUnit
 
@HiltWorker
class SyncWorker @AssistedInject constructor(
    @Assisted context: Context,
    @Assisted params: WorkerParameters,
    private val client: OkHttpClient,
) : CoroutineWorker(context, params) {
 
    override suspend fun doWork(): Result = withContext(Dispatchers.IO) {
        try {
            val request = Request.Builder().url("https://api.example.com/sync").build()
            client.newCall(request).execute().use { response ->
                when {
                    response.isSuccessful -> Result.success()
                    response.code >= 500 -> Result.retry()   // server trouble: back off and retry
                    else -> Result.failure()                 // 4xx: retrying will not help
                }
            }
        } catch (e: IOException) {
            Result.retry()
        }
    }
}
 
fun scheduleSync(context: Context) {
    val constraints = Constraints.Builder()
        .setRequiredNetworkType(NetworkType.UNMETERED)
        .setRequiresBatteryNotLow(true)
        .build()
 
    val work = PeriodicWorkRequestBuilder<SyncWorker>(6, TimeUnit.HOURS)
        .setConstraints(constraints)
        .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
        .build()
 
    WorkManager.getInstance(context)
        .enqueueUniquePeriodicWork("sync", ExistingPeriodicWorkPolicy.KEEP, work)
}
  • The client is a singleton, so every worker run and every repository share one connection pool and one cache. Creating a client inside the worker would throw both away on each run.
  • execute() blocks, so the worker moves it to Dispatchers.IO and closes the response with use.
  • UNMETERED plus setRequiresBatteryNotLow keeps a non-urgent sync off mobile data and off a nearly empty battery. The system picks the exact time, often batching it with other apps' jobs.
  • setBackoffCriteria controls the delay after Result.retry(). It is allowed here because the work does not use setRequiresDeviceIdle.
  • ExistingPeriodicWorkPolicy.KEEP keeps the existing schedule if scheduleSync runs on every app start.

Run the idea in plain Kotlin

class ConstrainedQueue {
  private val pending = mutableListOf<String>()
  var unmetered = false
      private set
  var charging = false
      private set

  fun enqueue(item: String) {
      pending.add(item)
      println("Queued " + item + " (pending: " + pending.size + ")")
  }

  fun update(unmetered: Boolean, charging: Boolean) {
      this.unmetered = unmetered
      this.charging = charging
      println("Conditions: unmetered=" + unmetered + ", charging=" + charging)
      if (unmetered && charging) flush()
  }

  private fun flush() {
      if (pending.isEmpty()) return
      println("Constraints met, one batch of " + pending.size + ": " + pending.joinToString(", "))
      pending.clear()
  }
}

fun main() {
  val queue = ConstrainedQueue()
  queue.enqueue("photo-1")
  queue.enqueue("photo-2")
  queue.update(unmetered = false, charging = true)
  queue.update(unmetered = true, charging = false)
  queue.enqueue("photo-3")
  queue.update(unmetered = true, charging = true)
}

Expected output:

Queued photo-1 (pending: 1)
Queued photo-2 (pending: 2)
Conditions: unmetered=false, charging=true
Conditions: unmetered=true, charging=false
Queued photo-3 (pending: 3)
Conditions: unmetered=true, charging=true
Constraints met, one batch of 3: photo-1, photo-2, photo-3

In production

Trip tracking held a wake lock for hours
  • A ride-hailing app acquired a PARTIAL_WAKE_LOCK when a trip started and requested GPS updates every second from a background service.
  • release() sat at the end of a try block, so an exception during trip shutdown skipped it and the lock stayed held until the process died.
  • Android vitals flagged excessive partial wake locks, and users reported heavy drain on days they took a single short trip.
The fix
  • Moved tracking into a foreground service with foregroundServiceType="location" and a visible trip notification, started only while a trip is active and stopped when it ends.
  • Removed the manual wake lock. Location updates come from FusedLocationProviderClient with a LocationRequest sized to the need (a few seconds during a trip, setMaxUpdateDelayMillis to batch updates when the screen is off).
  • Any remaining wake lock uses acquire(timeout) and release() in finally. Wake lock counts were then checked in Android vitals and with adb shell dumpsys power after each release.
News app re-downloaded everything on every cold start
  • The app built a new OkHttpClient for each API call, so no connection was reused and nothing was cached.
  • On cold start the home screen stayed blank while a dozen requests each did their own TLS handshake, and users on mobile data paid for the same JSON every launch.
The fix
  • Provided one OkHttpClient with a disk Cache from a Hilt @Singleton module and used it for Retrofit and image loading.
  • The backend added Cache-Control: max-age=300 and ETag headers to article lists, so OkHttp served repeat requests from disk or revalidated them cheaply.
  • The app stored articles in Room and showed them immediately on start, refreshing in the background (offline-first), so the first screen no longer waited for the network.

Common mistakes

  • Holding a wake lock without a timeout. A lock that is never released keeps the CPU awake. Prefer WorkManager, which holds a lock only while the worker runs; if you need your own, use acquire(timeoutMillis) and release() in finally.
  • Using exact alarms for periodic sync. Exact alarms need SCHEDULE_EXACT_ALARM on Android 12+ and wake the device on your schedule. For sync, use PeriodicWorkRequestBuilder (15-minute minimum) and let the system batch it.
  • Creating a new OkHttpClient per request. Each client has its own connection pool and cache, so you pay a new handshake and lose caching every time. Create one client and share it.
  • Requesting the battery optimization exemption for a normal app. Google Play restricts REQUEST_IGNORE_BATTERY_OPTIMIZATIONS to apps whose core feature needs it. A news or social app should rely on WorkManager and FCM instead.
  • Over-constraining work. Stacking setRequiresDeviceIdle(true) and setRequiresCharging(true) on user-visible sync can delay it for a long time on a phone that is rarely idle on a charger. Use the lightest constraints the work really needs.
  • Blaming the client for cache misses. If the server sends Cache-Control: no-store or no caching headers, OkHttp will not reuse the response. Check response.cacheResponse and response.networkResponse in a logging interceptor before changing the client.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What is Doze mode and how does it affect a background sync?”

“How do you schedule periodic background work in a modern Android app?”

“How does OkHttp caching work and when should a response not be cached?”

“How would you investigate a battery drain report?”

Quiz

What is the minimum repeat interval for a PeriodicWorkRequest in WorkManager?

Which of these does Doze NOT defer or block?

What happens if you create a new OkHttpClient for every HTTP request?

Which WorkManager setup throws an IllegalArgumentException when you build the request?

0 of 4 answered

Mini task

15-minute exercise: Add a cached, constrained sync

  1. Dependencies: add the current stable androidx.work:work-runtime-ktx, com.squareup.okhttp3:okhttp and, if you use Hilt, androidx.hilt:hilt-work.

  2. One client: provide a single OkHttpClient with .cache(Cache(File(cacheDir, "http_cache"), 20L * 1024 * 1024)) from a Hilt @Singleton module or your Application.

  3. Worker: write a CoroutineWorker that calls your sync endpoint on Dispatchers.IO, closes the response with use, and returns success() on 2xx, retry() on 5xx or IOException, failure() on 4xx.

  4. Schedule: enqueue it with enqueueUniquePeriodicWork("sync", ExistingPeriodicWorkPolicy.KEEP, ...) using NetworkType.UNMETERED, setRequiresBatteryNotLow(true) and setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS).

  5. Verify: run adb shell dumpsys jobscheduler, find your job and read its constraints. Turn Wi-Fi off and confirm it does not run; turn it on and watch logcat. Then run adb shell dumpsys battery unplug and adb shell dumpsys deviceidle force-idle and confirm the worker waits.

Done condition: the job appears in dumpsys jobscheduler with an unmetered network constraint, it runs only on Wi-Fi, and a second request to a cacheable endpoint shows a non-null cacheResponse in your logs.

Next: Crash handling and reporting