Battery and network efficiency
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
OkHttpClientwith a diskCachereuses 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().
| Mechanism | What it limits | API to know |
|---|---|---|
| Doze | Network, wake locks, alarms, jobs while idle | PowerManager.isDeviceIdleMode() |
| App Standby buckets | Jobs, alarms, network for rarely used apps | UsageStatsManager.getAppStandbyBucket() |
| WorkManager | Runs deferrable work when constraints are met | Constraints, PeriodicWorkRequestBuilder |
| OkHttp cache | Repeat downloads of the same response | Cache(directory, maxSize) |
| HTTP/2 | Separate connections per request | Negotiated 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()andsetExactAndAllowWhileIdle()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 unplugthenadb shell dumpsys deviceidle force-idle; undo withadb shell dumpsys deviceidle unforceandadb shell dumpsys battery reset. - WorkManager constraints:
setRequiredNetworkType(NetworkType.UNMETERED)for big downloads,CONNECTEDfor small syncs,setRequiresCharging(true)orsetRequiresBatteryNotLow(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 throwsIllegalArgumentExceptionif you combine it with backoff criteria.PeriodicWorkRequestBuilderenforces a 15-minute minimum interval. UseenqueueUniquePeriodicWorkwithExistingPeriodicWorkPolicy.KEEPso 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 infinally. - Exact alarms (
setExact(),setExactAndAllowWhileIdle()) need theSCHEDULE_EXACT_ALARMpermission 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_OPTIMIZATIONSasks 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-storeis never cached;max-agelets OkHttp serve the response without a request;ETaglets 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 toDispatchers.IOand closes the response withuse.UNMETEREDplussetRequiresBatteryNotLowkeeps 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.setBackoffCriteriacontrols the delay afterResult.retry(). It is allowed here because the work does not usesetRequiresDeviceIdle.ExistingPeriodicWorkPolicy.KEEPkeeps the existing schedule ifscheduleSyncruns 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
- A ride-hailing app acquired a
PARTIAL_WAKE_LOCKwhen a trip started and requested GPS updates every second from a background service. release()sat at the end of atryblock, 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.
- 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
FusedLocationProviderClientwith aLocationRequestsized to the need (a few seconds during a trip,setMaxUpdateDelayMillisto batch updates when the screen is off). - Any remaining wake lock uses
acquire(timeout)andrelease()infinally. Wake lock counts were then checked in Android vitals and withadb shell dumpsys powerafter each release.
- The app built a new
OkHttpClientfor 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.
- Provided one
OkHttpClientwith a diskCachefrom a Hilt@Singletonmodule and used it for Retrofit and image loading. - The backend added
Cache-Control: max-age=300andETagheaders 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)andrelease()infinally. - Using exact alarms for periodic sync. Exact alarms need
SCHEDULE_EXACT_ALARMon Android 12+ and wake the device on your schedule. For sync, usePeriodicWorkRequestBuilder(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_OPTIMIZATIONSto apps whose core feature needs it. A news or social app should rely on WorkManager and FCM instead. - Over-constraining work. Stacking
setRequiresDeviceIdle(true)andsetRequiresCharging(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-storeor no caching headers, OkHttp will not reuse the response. Checkresponse.cacheResponseandresponse.networkResponsein 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
-
Dependencies: add the current stable
androidx.work:work-runtime-ktx,com.squareup.okhttp3:okhttpand, if you use Hilt,androidx.hilt:hilt-work. -
One client: provide a single
OkHttpClientwith.cache(Cache(File(cacheDir, "http_cache"), 20L * 1024 * 1024))from a Hilt@Singletonmodule or yourApplication. -
Worker: write a
CoroutineWorkerthat calls your sync endpoint onDispatchers.IO, closes the response withuse, and returnssuccess()on 2xx,retry()on 5xx orIOException,failure()on 4xx. -
Schedule: enqueue it with
enqueueUniquePeriodicWork("sync", ExistingPeriodicWorkPolicy.KEEP, ...)usingNetworkType.UNMETERED,setRequiresBatteryNotLow(true)andsetBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS). -
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 runadb shell dumpsys battery unplugandadb shell dumpsys deviceidle force-idleand 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.