Skip to content

Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.

perf(android): poll for banking apps less while the screen is off (#61)

alexfoxtm6caa43f8a918
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/banking/BankingPollCadence.kt b/android/app/src/main/kotlin/app/nectarlink/android/banking/BankingPollCadence.kt
new file mode 100644
index 0000000..20d1d04
--- /dev/null
+++ b/android/app/src/main/kotlin/app/nectarlink/android/banking/BankingPollCadence.kt
@@ -0,0 +1,13 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package app.nectarlink.android.banking
+
+import kotlinx.coroutines.channels.Channel
+import kotlinx.coroutines.withTimeoutOrNull
+
+/** A long screen-off wait needs a registered receiver that can end it. */
+internal fun bankingPollWaitMs(screenInteractive: Boolean, wakeAvailable: Boolean, pollMs: Long, idleMs: Long): Long =
+ if (screenInteractive || !wakeAvailable) pollMs else idleMs
+
+/** Returns true when a screen return ended the wait. */
+internal suspend fun awaitScreenWake(waitMs: Long, wake: Channel<Unit>): Boolean =
+ withTimeoutOrNull(waitMs) { wake.receive(); true } ?: false
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt b/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt
index ea14225..f4cab7a 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt
@@ -5,11 +5,14 @@ import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
+import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
+import android.content.IntentFilter
import android.content.pm.ServiceInfo
import android.net.wifi.WifiManager
import android.os.Build
+import android.os.PowerManager
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.app.ServiceCompat
@@ -20,10 +23,13 @@ import app.nectarlink.android.NectarlinkApplication
import app.nectarlink.android.R
import app.nectarlink.android.banking.BankingPause
import app.nectarlink.android.banking.PauseDecider
+import app.nectarlink.android.banking.awaitScreenWake
+import app.nectarlink.android.banking.bankingPollWaitMs
import app.nectarlink.android.clipboard.SendActivity
import app.nectarlink.android.core.CoreState
import app.nectarlink.android.ui.MainActivity
import app.nectarlink.android.ui.Preferences
+import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
@@ -37,6 +43,11 @@ import kotlinx.coroutines.launch
*/
class ConnectionService : LifecycleService() {
private var multicastLock: WifiManager.MulticastLock? = null
+ private var screenReceiver: BroadcastReceiver? = null
+ /** False when [registerScreenWake] did not stick. The poll must not idle for 15s with no wake. */
+ @Volatile private var screenWakeRegistered = false
+ /** One pending screen return is enough. A burst must not queue a spin. */
+ private val screenWake = Channel<Unit>(Channel.CONFLATED)
override fun onCreate() {
super.onCreate()
@@ -55,6 +66,7 @@ class ConnectionService : LifecycleService() {
multicastLock = getSystemService(WifiManager::class.java)
?.createMulticastLock("nectarlink-discovery")
?.apply { setReferenceCounted(false); acquire() }
+ registerScreenWake()
lifecycleScope.launch {
core.state.map { Status.of(it) to (it.status is app.nectarlink.android.core.CoreStatus.Ready) }
@@ -78,23 +90,29 @@ class ConnectionService : LifecycleService() {
}
}
// Pause for banking apps: follow the app in front while it's set up.
+ // Screen returns end the idle wait and start a fresh resume countdown.
lifecycleScope.launch(kotlinx.coroutines.Dispatchers.Default) {
val context = applicationContext
- val decider = PauseDecider()
+ val power = getSystemService(PowerManager::class.java)
+ var decider = PauseDecider()
var foreground: BankingPause.Foreground? = null
while (true) {
if (!BankingPause.isReady(context)) {
foreground = null
+ decider = PauseDecider()
delay(BANKING_IDLE_MS)
continue
}
val follow = foreground ?: BankingPause.Foreground(context).also { foreground = it }
- when (decider.decide(follow.poll(), BankingPause.apps(context), BankingPause.isPaused(context), System.currentTimeMillis())) {
+ val pkg = follow.poll()
+ if (screenWake.tryReceive().isSuccess || pkg == null) decider = PauseDecider()
+ when (decider.decide(pkg, BankingPause.apps(context), BankingPause.isPaused(context), System.currentTimeMillis())) {
PauseDecider.Action.PAUSE -> BankingPause.pause(context)
PauseDecider.Action.RESUME -> BankingPause.resume(context)
null -> {}
}
- delay(BANKING_POLL_MS)
+ val wait = bankingPollWaitMs(power?.isInteractive != false, screenWakeRegistered, BANKING_POLL_MS, BANKING_IDLE_MS)
+ if (awaitScreenWake(wait, screenWake)) decider = PauseDecider()
}
}
lifecycleScope.launch {
@@ -121,11 +139,48 @@ class ConnectionService : LifecycleService() {
}
override fun onDestroy() {
+ unregisterScreenWake()
multicastLock?.runCatching { release() }
getSystemService(NotificationManager::class.java)?.cancel(ONGOING_ID)
super.onDestroy()
}
+ /**
+ * Screen on and user present are system broadcasts. Registered only while
+ * this service is alive, so a restart cannot leave a receiver behind, and
+ * the receiver does not start the service.
+ */
+ private fun registerScreenWake() {
+ if (screenReceiver != null) return
+ val receiver = object : BroadcastReceiver() {
+ override fun onReceive(context: Context, intent: Intent) {
+ val action = intent.action
+ if (action != Intent.ACTION_SCREEN_ON && action != Intent.ACTION_USER_PRESENT) return
+ screenWake.trySend(Unit)
+ }
+ }
+ val filter = IntentFilter().apply {
+ addAction(Intent.ACTION_SCREEN_ON)
+ addAction(Intent.ACTION_USER_PRESENT)
+ }
+ val registered = runCatching {
+ ContextCompat.registerReceiver(this, receiver, filter, ContextCompat.RECEIVER_NOT_EXPORTED)
+ }.onFailure {
+ Log.w(TAG, "screen wake receiver failed", it)
+ }.isSuccess
+ if (!registered) return
+ screenReceiver = receiver
+ screenWakeRegistered = true
+ }
+
+ private fun unregisterScreenWake() {
+ // Drop the flag first so a poll still in the loop cannot idle with the receiver already gone.
+ screenWakeRegistered = false
+ val receiver = screenReceiver ?: return
+ screenReceiver = null
+ runCatching { unregisterReceiver(receiver) }
+ }
+
private fun startInForeground(state: CoreState): Boolean = runCatching {
val type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE
@@ -206,8 +261,9 @@ class ConnectionService : LifecycleService() {
companion object {
private const val TAG = "Nectarlink"
private const val UPDATE_WAKE_MS = 6L * 3600 * 1000
- /** How often to look at the app in front when Pause for banking apps is set up, and when it isn't. */
+ /** How often to look at the app in front while the screen is on and Pause for banking apps is set up. */
private const val BANKING_POLL_MS = 800L
+ /** Screen off, or Pause for banking apps is not set up. */
private const val BANKING_IDLE_MS = 15_000L
private const val ONGOING_ID = 1
private const val RINGING_ID = 2
diff --git a/android/app/src/test/kotlin/app/nectarlink/android/banking/BankingPollCadenceTest.kt b/android/app/src/test/kotlin/app/nectarlink/android/banking/BankingPollCadenceTest.kt
new file mode 100644
index 0000000..87c120e
--- /dev/null
+++ b/android/app/src/test/kotlin/app/nectarlink/android/banking/BankingPollCadenceTest.kt
@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package app.nectarlink.android.banking
+
+import kotlinx.coroutines.CoroutineStart
+import kotlinx.coroutines.async
+import kotlinx.coroutines.channels.Channel
+import kotlinx.coroutines.runBlocking
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class BankingPollCadenceTest {
+ private val pollMs = 800L
+ private val idleMs = 15_000L
+
+ @Test
+ fun screenOffIdlesWithAReceiverAndScreenReturnEndsTheWait() = runBlocking {
+ assertEquals(idleMs, bankingPollWaitMs(false, true, pollMs, idleMs))
+ assertEquals(pollMs, bankingPollWaitMs(true, true, pollMs, idleMs))
+ val wake = Channel<Unit>(Channel.CONFLATED)
+ val waiting = async(start = CoroutineStart.UNDISPATCHED) { awaitScreenWake(idleMs, wake) }
+ assertFalse(waiting.isCompleted)
+ wake.trySend(Unit)
+ assertTrue(waiting.await())
+ assertTrue(wake.tryReceive().isFailure)
+ }
+
+ @Test
+ fun receiverFailureKeepsTheShortPollAndTimeoutDoesNotReportAWake() = runBlocking {
+ assertEquals(pollMs, bankingPollWaitMs(false, false, pollMs, idleMs))
+ assertEquals(pollMs, bankingPollWaitMs(true, false, pollMs, idleMs))
+ assertFalse(awaitScreenWake(1L, Channel(Channel.CONFLATED)))
+ }
+}