BatteryExemption.kt

2.0 KB · raw

1package com.peachpasswords.sync23import android.content.Context4import android.content.Intent5import android.net.Uri6import android.os.PowerManager7import android.provider.Settings89/**10 * Asks once to be left out of Doze / App Standby.11 *12 * Without it, a phone that has been idle for a while stops answering, and the13 * failure is invisible: a browser dialing a cached address just times out, which14 * is indistinguishable from the phone being off the network. The foreground15 * service keeps the process alive but does not by itself stop Doze from16 * deferring network work.17 *18 * Deliberately only offered once and never nagged — the system dialog is19 * alarming ("let this app run in the background all the time?"), and a user who20 * says no should get a phone that syncs when they open the app rather than one21 * that keeps asking. [isExempt] lets settings show the real state instead of22 * assuming the request worked.23 */24object BatteryExemption {2526    private const val PREFS = "peach_sync_battery"27    private const val ASKED_KEY = "asked_exemption"2829    fun isExempt(context: Context): Boolean {30        val pm = context.getSystemService(Context.POWER_SERVICE) as? PowerManager ?: return false31        return pm.isIgnoringBatteryOptimizations(context.packageName)32    }3334    fun shouldAsk(context: Context): Boolean =35        !isExempt(context) && !context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)36            .getBoolean(ASKED_KEY, false)3738    /**39     * Returns the intent to launch, or null when there is nothing to ask for.40     * The caller launches it so the result lands on a real Activity.41     */42    fun requestIntent(context: Context): Intent? {43        if (!shouldAsk(context)) return null44        context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)45            .edit().putBoolean(ASKED_KEY, true).apply()46        return Intent(47            Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS,48            Uri.parse("package:${context.packageName}"),49        )50    }51}