package com.peachpasswords.sync import android.content.Context import android.content.Intent import android.net.Uri import android.os.PowerManager import android.provider.Settings /** * Asks once to be left out of Doze / App Standby. * * Without it, a phone that has been idle for a while stops answering, and the * failure is invisible: a browser dialing a cached address just times out, which * is indistinguishable from the phone being off the network. The foreground * service keeps the process alive but does not by itself stop Doze from * deferring network work. * * Deliberately only offered once and never nagged — the system dialog is * alarming ("let this app run in the background all the time?"), and a user who * says no should get a phone that syncs when they open the app rather than one * that keeps asking. [isExempt] lets settings show the real state instead of * assuming the request worked. */ object BatteryExemption { private const val PREFS = "peach_sync_battery" private const val ASKED_KEY = "asked_exemption" fun isExempt(context: Context): Boolean { val pm = context.getSystemService(Context.POWER_SERVICE) as? PowerManager ?: return false return pm.isIgnoringBatteryOptimizations(context.packageName) } fun shouldAsk(context: Context): Boolean = !isExempt(context) && !context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) .getBoolean(ASKED_KEY, false) /** * Returns the intent to launch, or null when there is nothing to ask for. * The caller launches it so the result lands on a real Activity. */ fun requestIntent(context: Context): Intent? { if (!shouldAsk(context)) return null context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) .edit().putBoolean(ASKED_KEY, true).apply() return Intent( Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, Uri.parse("package:${context.packageName}"), ) } }