Skip to content

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

Android: pause for banking apps

Bee47be114f3ffc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7098fc2..97e80c4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,15 @@ change things that need a step from you, and its notes say so.
## Unreleased
+### New
+
+- **Pause for banking apps.** Many banking apps won't open while Developer
+ options, debugging or an accessibility service is on. Choose them in
+ **Settings › Control from your PC**: while one is open, NectarLink turns
+ those off, and turns back on exactly what was on when you leave, even after
+ a crash or a restart. A shortcut can pause first for apps that check as
+ they open.
+
### Fixed
- **Windows 10.** NectarLink and its installer start on Windows 10 again. They
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index 8a4c0b8..0cdf299 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -33,6 +33,11 @@
<uses-permission
android:name="android.permission.WRITE_SECURE_SETTINGS"
tools:ignore="ProtectedPermissions" />
+ <!-- Pause for banking apps: which app is in front (usage access, granted
+ by Elevated or in Settings › Usage access). -->
+ <uses-permission
+ android:name="android.permission.PACKAGE_USAGE_STATS"
+ tools:ignore="ProtectedPermissions" />
<!-- Quick settings from a PC: Do Not Disturb / silent mode, and screen
brightness (asked for in Settings, or granted at Elevated). -->
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />
@@ -251,6 +256,19 @@
android:taskAffinity=""
android:theme="@android:style/Theme.Translucent.NoTitleBar" />
+ <!-- Pause for banking apps: "Open with banking pause" shortcuts, and
+ the paused notification's Turn back on. -->
+ <activity
+ android:name=".banking.OpenWithPauseActivity"
+ android:exported="false"
+ android:excludeFromRecents="true"
+ android:noHistory="true"
+ android:taskAffinity=""
+ android:theme="@android:style/Theme.Translucent.NoTitleBar" />
+ <receiver
+ android:name=".banking.BankingPause$ResumeReceiver"
+ android:exported="false" />
+
<!-- The PC's mouse and keyboard on the mirrored screen (Assist); the
user turns it on in Android's accessibility settings. -->
<service
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/NectarlinkApplication.kt b/android/app/src/main/kotlin/app/nectarlink/android/NectarlinkApplication.kt
index 258730a..d5fe800 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/NectarlinkApplication.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/NectarlinkApplication.kt
@@ -2,6 +2,7 @@
package app.nectarlink.android
import android.app.Application
+import app.nectarlink.android.banking.BankingPause
import app.nectarlink.android.core.Core
import app.nectarlink.android.elevated.Elevated
import app.nectarlink.android.update.AppUpdater
@@ -21,6 +22,9 @@ class NectarlinkApplication : Application() {
override fun onCreate() {
super.onCreate()
+ // Before Elevated: it waits while paused for a banking app.
+ BankingPause.init(this)
+ BankingPause.restoreIfStranded(this)
Elevated.init(this)
// What the phone offers PCs follows Elevated starting and stopping.
Elevated.onChange = { core.refreshNotificationAccess() }
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/banking/BankingPause.kt b/android/app/src/main/kotlin/app/nectarlink/android/banking/BankingPause.kt
new file mode 100644
index 0000000..331bcbc
--- /dev/null
+++ b/android/app/src/main/kotlin/app/nectarlink/android/banking/BankingPause.kt
@@ -0,0 +1,246 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package app.nectarlink.android.banking
+
+import android.Manifest
+import android.app.AppOpsManager
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.PendingIntent
+import android.app.usage.UsageEvents
+import android.app.usage.UsageStatsManager
+import android.content.BroadcastReceiver
+import android.content.ComponentName
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.os.Build
+import android.os.PowerManager
+import android.os.Process
+import android.provider.Settings
+import android.util.Log
+import androidx.core.app.NotificationCompat
+import androidx.core.content.edit
+import app.nectarlink.android.R
+import app.nectarlink.android.elevated.Elevated
+import app.nectarlink.android.mirror.InputService
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+
+/**
+ * Pause for banking apps: many banking apps refuse to run while Developer
+ * options, USB or Wireless debugging are on, or while an accessibility
+ * service is enabled, all of which NectarLink's Elevated and Assist use.
+ * While an app the user chose is in front, NectarLink turns those off, and
+ * turns back on exactly what it turned off once the user leaves.
+ *
+ * Changing them needs WRITE_SECURE_SETTINGS (Elevated grants it once), and
+ * knowing the app in front needs usage access. What was turned off is saved
+ * before anything changes, so it comes back after a crash or a reboot too.
+ */
+object BankingPause {
+ private const val TAG = "BankingPause"
+ private const val PREFS = "banking_pause"
+ private const val APPS = "apps"
+ /** Saved while paused: what was on before, to turn back on. */
+ private const val PAUSED = "paused"
+ private const val WAS_DEVELOPER = "was_developer"
+ private const val WAS_USB_DEBUGGING = "was_usb_debugging"
+ private const val WAS_WIRELESS_DEBUGGING = "was_wireless_debugging"
+ private const val WAS_ACCESSIBILITY = "was_accessibility"
+
+ private const val DEVELOPER = Settings.Global.DEVELOPMENT_SETTINGS_ENABLED
+ private const val USB_DEBUGGING = Settings.Global.ADB_ENABLED
+ private const val WIRELESS_DEBUGGING = "adb_wifi_enabled"
+
+ private const val CHANNEL = "banking_pause"
+ private const val NOTIFICATION_ID = 41
+ private const val ACTION_RESUME = "app.nectarlink.action.BANKING_RESUME"
+
+ private val _paused = MutableStateFlow(false)
+ /** Whether things are paused for a banking app now. */
+ val paused: StateFlow<Boolean> = _paused.asStateFlow()
+
+ private fun prefs(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
+
+ /** Brings the in-memory state in line with what's saved (at process start). */
+ fun init(context: Context) {
+ _paused.value = prefs(context).getBoolean(PAUSED, false)
+ }
+
+ fun isPaused(context: Context): Boolean = prefs(context).getBoolean(PAUSED, false)
+
+ /** The banking apps the user chose, by package. */
+ fun apps(context: Context): Set<String> = prefs(context).getStringSet(APPS, emptySet()).orEmpty().toSet()
+
+ fun setApps(context: Context, apps: Set<String>) {
+ prefs(context).edit { putStringSet(APPS, apps.toSet()) }
+ // Removing the app that's paused for leaves nothing to stay paused for.
+ if (apps.isEmpty() && isPaused(context)) resume(context)
+ }
+
+ /** Whether NectarLink may change these settings (granted when Elevated first starts). */
+ fun canChangeSettings(context: Context): Boolean =
+ context.checkSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS) == PackageManager.PERMISSION_GRANTED
+
+ /** Whether NectarLink can see which app is in front (Settings › Usage access). */
+ fun hasUsageAccess(context: Context): Boolean {
+ val ops = context.getSystemService(AppOpsManager::class.java) ?: return false
+ val mode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ ops.unsafeCheckOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, Process.myUid(), context.packageName)
+ } else {
+ @Suppress("DEPRECATION")
+ ops.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, Process.myUid(), context.packageName)
+ }
+ return mode == AppOpsManager.MODE_ALLOWED
+ }
+
+ /** Ready to work: something chosen, and both permissions. */
+ fun isReady(context: Context): Boolean =
+ apps(context).isNotEmpty() && canChangeSettings(context) && hasUsageAccess(context)
+
+ /**
+ * Turns off Developer options, USB and Wireless debugging and NectarLink's
+ * accessibility service, saving what was on first. Does nothing if
+ * already paused or not allowed.
+ */
+ @Synchronized
+ fun pause(context: Context) {
+ if (isPaused(context) || !canChangeSettings(context)) return
+ val resolver = context.contentResolver
+ val accessibility = isAccessibilityEnabled(context)
+ // Saved before anything changes, so a crash halfway still restores.
+ prefs(context).edit(commit = true) {
+ putBoolean(PAUSED, true)
+ putBoolean(WAS_DEVELOPER, global(context, DEVELOPER))
+ putBoolean(WAS_USB_DEBUGGING, global(context, USB_DEBUGGING))
+ putBoolean(WAS_WIRELESS_DEBUGGING, global(context, WIRELESS_DEBUGGING))
+ putBoolean(WAS_ACCESSIBILITY, accessibility)
+ }
+ _paused.value = true
+ runCatching {
+ if (accessibility) setAccessibility(context, false)
+ Settings.Global.putInt(resolver, WIRELESS_DEBUGGING, 0)
+ Settings.Global.putInt(resolver, USB_DEBUGGING, 0)
+ Settings.Global.putInt(resolver, DEVELOPER, 0)
+ }.onFailure { Log.w(TAG, "couldn't pause everything", it) }
+ Log.i(TAG, "paused for a banking app")
+ showNotification(context)
+ }
+
+ /** Turns back on exactly what [pause] turned off. */
+ @Synchronized
+ fun resume(context: Context) {
+ val saved = prefs(context)
+ if (!saved.getBoolean(PAUSED, false)) return
+ val resolver = context.contentResolver
+ runCatching {
+ if (saved.getBoolean(WAS_DEVELOPER, false)) Settings.Global.putInt(resolver, DEVELOPER, 1)
+ if (saved.getBoolean(WAS_USB_DEBUGGING, false)) Settings.Global.putInt(resolver, USB_DEBUGGING, 1)
+ if (saved.getBoolean(WAS_WIRELESS_DEBUGGING, false)) Settings.Global.putInt(resolver, WIRELESS_DEBUGGING, 1)
+ if (saved.getBoolean(WAS_ACCESSIBILITY, false)) setAccessibility(context, true)
+ }.onFailure { Log.w(TAG, "couldn't turn everything back on", it) }
+ saved.edit(commit = true) {
+ remove(PAUSED)
+ remove(WAS_DEVELOPER)
+ remove(WAS_USB_DEBUGGING)
+ remove(WAS_WIRELESS_DEBUGGING)
+ remove(WAS_ACCESSIBILITY)
+ }
+ _paused.value = false
+ Log.i(TAG, "turned back on after a banking app")
+ context.getSystemService(NotificationManager::class.java)?.cancel(NOTIFICATION_ID)
+ // Elevated waited while paused; with debugging back it starts again.
+ Elevated.onNetworkChanged()
+ }
+
+ /** At process start: a pause left over from before (a crash, a reboot) with nothing to wait for ends now. */
+ fun restoreIfStranded(context: Context) {
+ if (isPaused(context) && !isReady(context)) resume(context)
+ }
+
+ private fun global(context: Context, name: String): Boolean =
+ runCatching { Settings.Global.getInt(context.contentResolver, name, 0) == 1 }.getOrDefault(false)
+
+ private fun accessibilityComponent(context: Context): String =
+ ComponentName(context, InputService::class.java).flattenToString()
+
+ private fun isAccessibilityEnabled(context: Context): Boolean {
+ val enabled = Settings.Secure.getString(context.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES)
+ return enabled?.split(':')?.any { it.equals(accessibilityComponent(context), ignoreCase = true) } == true
+ }
+
+ private fun setAccessibility(context: Context, on: Boolean) {
+ val resolver = context.contentResolver
+ val ours = accessibilityComponent(context)
+ val others = Settings.Secure.getString(resolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES)
+ ?.split(':')
+ ?.filter { it.isNotBlank() && !it.equals(ours, ignoreCase = true) }
+ .orEmpty()
+ val services = if (on) others + ours else others
+ Settings.Secure.putString(resolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, services.joinToString(":"))
+ Settings.Secure.putInt(resolver, Settings.Secure.ACCESSIBILITY_ENABLED, if (services.isEmpty()) 0 else 1)
+ }
+
+ // ---- The app in front ----
+
+ /** Follows the app in front from usage events. */
+ class Foreground(context: Context) {
+ private val usage = context.getSystemService(UsageStatsManager::class.java)
+ private val power = context.getSystemService(PowerManager::class.java)
+ /** The first read looks back an hour, to know what's in front already. */
+ private var lastQueryMs = System.currentTimeMillis() - 3_600_000
+ /** The app last brought to the front, as far as the events say. */
+ var current: String? = null
+ private set
+
+ /** Reads the events since the last call; returns the app in front (null when the screen is off). */
+ fun poll(): String? {
+ if (power?.isInteractive == false) return null
+ val now = System.currentTimeMillis()
+ val events = runCatching { usage?.queryEvents(lastQueryMs, now) }.getOrNull()
+ lastQueryMs = now
+ if (events != null) {
+ val event = UsageEvents.Event()
+ while (events.hasNextEvent()) {
+ events.getNextEvent(event)
+ // ACTIVITY_RESUMED (Android 10+) has the same value.
+ @Suppress("DEPRECATION")
+ if (event.eventType == UsageEvents.Event.MOVE_TO_FOREGROUND) current = event.packageName
+ }
+ }
+ return current
+ }
+ }
+
+ // ---- The notification while paused ----
+
+ private fun showNotification(context: Context) {
+ val manager = context.getSystemService(NotificationManager::class.java) ?: return
+ manager.createNotificationChannel(
+ NotificationChannel(CHANNEL, context.getString(R.string.banking_channel), NotificationManager.IMPORTANCE_LOW)
+ .apply { setShowBadge(false) },
+ )
+ val resume = PendingIntent.getBroadcast(
+ context, 0, Intent(context, ResumeReceiver::class.java).setAction(ACTION_RESUME),
+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
+ )
+ val notification = NotificationCompat.Builder(context, CHANNEL)
+ .setSmallIcon(R.drawable.ic_notification)
+ .setContentTitle(context.getString(R.string.banking_paused_title))
+ .setContentText(context.getString(R.string.banking_paused_text))
+ .setOngoing(true)
+ .setSilent(true)
+ .setCategory(NotificationCompat.CATEGORY_STATUS)
+ .addAction(0, context.getString(R.string.banking_turn_back_on), resume)
+ .build()
+ runCatching { manager.notify(NOTIFICATION_ID, notification) }
+ }
+
+ /** The notification's Turn back on. */
+ class ResumeReceiver : BroadcastReceiver() {
+ override fun onReceive(context: Context, intent: Intent) {
+ if (intent.action == ACTION_RESUME) resume(context.applicationContext)
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/banking/OpenWithPauseActivity.kt b/android/app/src/main/kotlin/app/nectarlink/android/banking/OpenWithPauseActivity.kt
new file mode 100644
index 0000000..2e188d6
--- /dev/null
+++ b/android/app/src/main/kotlin/app/nectarlink/android/banking/OpenWithPauseActivity.kt
@@ -0,0 +1,59 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package app.nectarlink.android.banking
+
+import android.app.Activity
+import android.content.Context
+import android.content.Intent
+import android.content.pm.ShortcutInfo
+import android.content.pm.ShortcutManager
+import android.graphics.drawable.Icon
+import android.os.Bundle
+import android.util.Log
+import androidx.core.graphics.drawable.toBitmap
+
+/**
+ * Behind an "Open with banking pause" home screen shortcut: pauses first,
+ * then opens the banking app, for apps that check as they start, before
+ * NectarLink could notice them in front.
+ */
+class OpenWithPauseActivity : Activity() {
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ val pkg = intent.getStringExtra(EXTRA_PACKAGE)
+ if (pkg != null && pkg in BankingPause.apps(this)) {
+ BankingPause.pause(applicationContext)
+ packageManager.getLaunchIntentForPackage(pkg)?.let { launch ->
+ runCatching { startActivity(launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }
+ .onFailure { Log.w(TAG, "couldn't open the banking app", it) }
+ }
+ }
+ finish()
+ }
+
+ companion object {
+ private const val TAG = "BankingPause"
+ private const val EXTRA_PACKAGE = "package"
+
+ /** Whether this launcher can take a pinned shortcut. */
+ fun canPin(context: Context): Boolean =
+ context.getSystemService(ShortcutManager::class.java)?.isRequestPinShortcutSupported == true
+
+ /** Asks the launcher to add an "Open with banking pause" shortcut for [pkg]. */
+ fun pin(context: Context, pkg: String, label: String): Boolean = runCatching {
+ val manager = context.getSystemService(ShortcutManager::class.java) ?: return false
+ val intent = Intent(context, OpenWithPauseActivity::class.java)
+ .setAction(Intent.ACTION_VIEW)
+ .putExtra(EXTRA_PACKAGE, pkg)
+ val bitmap = context.packageManager.getApplicationIcon(pkg).toBitmap(ICON_PX, ICON_PX)
+ val shortcut = ShortcutInfo.Builder(context, "banking_$pkg")
+ .setShortLabel(label)
+ .setLongLabel(label)
+ .setIcon(Icon.createWithBitmap(bitmap))
+ .setIntent(intent)
+ .build()
+ manager.requestPinShortcut(shortcut, null)
+ }.onFailure { Log.w(TAG, "couldn't add the shortcut", it) }.getOrDefault(false)
+
+ private const val ICON_PX = 192
+ }
+}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/banking/PauseDecider.kt b/android/app/src/main/kotlin/app/nectarlink/android/banking/PauseDecider.kt
new file mode 100644
index 0000000..5662069
--- /dev/null
+++ b/android/app/src/main/kotlin/app/nectarlink/android/banking/PauseDecider.kt
@@ -0,0 +1,58 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package app.nectarlink.android.banking
+
+/**
+ * When to pause for banking apps, and when to turn things back on, from the
+ * app in front as it changes. Kept apart from Android so it can be tested.
+ *
+ * - A chosen banking app comes to the front: pause right away (most banking
+ * apps check as they open).
+ * - Something else stays in front for [resumeAfterMs]: turn things back on.
+ * The wait lets a banking app hand over to another one and back (a UPI
+ * payment, say) without switching settings on and off in between.
+ * - Screens Android puts over any app (permission prompts, the system UI)
+ * change nothing: they show over a banking app as often as over others.
+ */
+class PauseDecider(
+ private val resumeAfterMs: Long = RESUME_AFTER_MS,
+ private val neutral: Set<String> = NEUTRAL_PACKAGES,
+) {
+ enum class Action { PAUSE, RESUME }
+
+ private var otherSinceMs: Long? = null
+
+ /**
+ * The app in front is [foreground] (null when unknown) at [nowMs];
+ * [paused] says whether things are paused now. Returns what to do, if
+ * anything.
+ */
+ fun decide(foreground: String?, apps: Set<String>, paused: Boolean, nowMs: Long): Action? {
+ if (foreground == null || foreground in neutral) return null
+ if (foreground in apps) {
+ otherSinceMs = null
+ return if (paused) null else Action.PAUSE
+ }
+ if (!paused) {
+ otherSinceMs = null
+ return null
+ }
+ val since = otherSinceMs ?: nowMs.also { otherSinceMs = it }
+ if (nowMs - since < resumeAfterMs) return null
+ otherSinceMs = null
+ return Action.RESUME
+ }
+
+ companion object {
+ const val RESUME_AFTER_MS = 3_000L
+
+ /** Shown over any app: the system UI and permission and install prompts. */
+ val NEUTRAL_PACKAGES = setOf(
+ "android",
+ "com.android.systemui",
+ "com.android.permissioncontroller",
+ "com.google.android.permissioncontroller",
+ "com.android.packageinstaller",
+ "com.google.android.packageinstaller",
+ )
+ }
+}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/elevated/Elevated.kt b/android/app/src/main/kotlin/app/nectarlink/android/elevated/Elevated.kt
index 7a2298a..615aec0 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/elevated/Elevated.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/elevated/Elevated.kt
@@ -17,6 +17,7 @@ import android.util.Log
import android.view.KeyEvent
import android.view.WindowManager
import androidx.core.content.edit
+import app.nectarlink.android.banking.BankingPause
import app.nectarlink.android.calls.CallCompanion
import app.nectarlink.android.notifications.NotificationListener
import app.nectarlink.core.MirrorInputEvent
@@ -151,7 +152,7 @@ object Elevated {
/** Tries again later, while it can still work: paired, not running, on Wi-Fi. */
private fun scheduleRetry() {
- if (!paired() || running || !onWifi()) return
+ if (!paired() || running || !onWifi() || BankingPause.isPaused(context)) return
val wait = RETRY_MS[retryAttempt.coerceAtMost(RETRY_MS.lastIndex)]
retryAttempt++
retryJob?.cancel()
@@ -243,6 +244,12 @@ object Elevated {
/** Connects and starts the input helper (when set up or rooted; again after it stopped). */
suspend fun start(): Boolean = withContext(Dispatchers.IO) {
if (!paired() && !isRootAvailable()) return@withContext false
+ // Paused for a banking app: debugging stays off until it's over
+ // (BankingPause starts Elevated again then).
+ if (BankingPause.isPaused(context)) {
+ if (!running) _state.value = State.Waiting
+ return@withContext false
+ }
val started = lock.withLock {
if (running) return@withLock true
_state.value = State.Starting
@@ -379,6 +386,10 @@ object Elevated {
if (!Settings.System.canWrite(context)) {
run(adb, "appops set ${context.packageName} WRITE_SETTINGS allow")
}
+ // Pause for banking apps sees which app is in front; only for those using it.
+ if (BankingPause.apps(context).isNotEmpty() && !BankingPause.hasUsageAccess(context)) {
+ run(adb, "appops set ${context.packageName} GET_USAGE_STATS allow")
+ }
val token = ByteArray(24).also(SecureRandom()::nextBytes).joinToString("") { "%02x".format(it) }
val apk = context.applicationInfo.sourceDir
val command = "CLASSPATH=$apk app_process /system/bin ${InputServer::class.java.name} $token"
@@ -597,6 +608,9 @@ object Elevated {
}.onFailure { Log.w(TAG, "can't open Elevated audio stream", it) }.getOrNull()
}
+ /** Lets NectarLink see which app is in front (for Pause for banking apps); false if Elevated isn't running. */
+ fun grantUsageAccess(): Boolean = runCommand("appops set ${context.packageName} GET_USAGE_STATS allow")
+
/** Runs an allowed shell command through the Elevated helper. */
fun runCommand(command: String): Boolean {
val writer = input ?: return false
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/elevated/InputServer.kt b/android/app/src/main/kotlin/app/nectarlink/android/elevated/InputServer.kt
index 7150864..374ff1d 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/elevated/InputServer.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/elevated/InputServer.kt
@@ -741,6 +741,8 @@ object InputServer {
"hotspot off",
"cmd wifi start-softap",
"cmd wifi stop-softap",
+ // Pause for banking apps: seeing which app is in front.
+ "appops set app.nectarlink GET_USAGE_STATS allow",
)
private companion object {
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 239c2b7..a86aee3 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
@@ -18,6 +18,8 @@ import androidx.lifecycle.LifecycleService
import androidx.lifecycle.lifecycleScope
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.clipboard.SendActivity
import app.nectarlink.android.core.CoreState
import app.nectarlink.android.ui.MainActivity
@@ -74,6 +76,26 @@ class ConnectionService : LifecycleService() {
delay(UPDATE_WAKE_MS)
}
}
+ // Pause for banking apps: follow the app in front while it's set up.
+ lifecycleScope.launch(kotlinx.coroutines.Dispatchers.Default) {
+ val context = applicationContext
+ val decider = PauseDecider()
+ var foreground: BankingPause.Foreground? = null
+ while (true) {
+ if (!BankingPause.isReady(context)) {
+ foreground = null
+ 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())) {
+ PauseDecider.Action.PAUSE -> BankingPause.pause(context)
+ PauseDecider.Action.RESUME -> BankingPause.resume(context)
+ null -> {}
+ }
+ delay(BANKING_POLL_MS)
+ }
+ }
lifecycleScope.launch {
core.state.map { it.ringingFrom }.distinctUntilChanged().collect { from ->
val manager = getSystemService(NotificationManager::class.java)
@@ -170,6 +192,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. */
+ private const val BANKING_POLL_MS = 800L
+ private const val BANKING_IDLE_MS = 15_000L
private const val ONGOING_ID = 1
private const val RINGING_ID = 2
private const val CHANNEL_CONNECTION = "connection"
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/BankingPauseSettings.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/BankingPauseSettings.kt
new file mode 100644
index 0000000..5f51188
--- /dev/null
+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/BankingPauseSettings.kt
@@ -0,0 +1,223 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package app.nectarlink.android.ui.settings
+
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.provider.Settings
+import androidx.compose.foundation.Image
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.items
+import androidx.compose.material3.AlertDialog
+import androidx.compose.material3.Button
+import androidx.compose.material3.Checkbox
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedButton
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.ImageBitmap
+import androidx.compose.ui.graphics.asImageBitmap
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.res.pluralStringResource
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.unit.dp
+import androidx.core.graphics.drawable.toBitmap
+import androidx.lifecycle.compose.LifecycleResumeEffect
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import app.nectarlink.android.R
+import app.nectarlink.android.banking.BankingPause
+import app.nectarlink.android.banking.OpenWithPauseActivity
+import app.nectarlink.android.elevated.Elevated
+
+/** An app the user can choose: package, name and a small icon. */
+private data class Choosable(val pkg: String, val label: String, val icon: ImageBitmap?)
+
+/** Settings › Control › Pause for banking apps. */
+@Composable
+internal fun BankingPauseAccess() {
+ val context = LocalContext.current
+ var chosen by remember { mutableStateOf(BankingPause.apps(context)) }
+ var canChange by remember { mutableStateOf(BankingPause.canChangeSettings(context)) }
+ var usage by remember { mutableStateOf(BankingPause.hasUsageAccess(context)) }
+ var picking by remember { mutableStateOf(false) }
+ val paused by BankingPause.paused.collectAsStateWithLifecycle()
+ // Permissions can change in Settings while NectarLink is in the background.
+ LifecycleResumeEffect(Unit) {
+ canChange = BankingPause.canChangeSettings(context)
+ usage = BankingPause.hasUsageAccess(context)
+ onPauseOrDispose {}
+ }
+
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
+ Column(Modifier.weight(1f).padding(end = 12.dp)) {
+ Text(stringResource(R.string.banking_title), style = MaterialTheme.typography.titleSmall)
+ Text(
+ if (chosen.isEmpty()) {
+ stringResource(R.string.banking_text)
+ } else {
+ pluralStringResource(R.plurals.banking_chosen, chosen.size, chosen.size)
+ },
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+ OutlinedButton(onClick = { picking = true }) { Text(stringResource(R.string.banking_choose)) }
+ }
+
+ if (chosen.isNotEmpty()) {
+ when {
+ !canChange -> Note(stringResource(R.string.banking_needs_elevated))
+ !usage -> Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
+ Note(stringResource(R.string.banking_needs_usage), Modifier.weight(1f).padding(end = 12.dp))
+ Button(onClick = {
+ // Through Elevated when it's running, else Android's own page.
+ if (!Elevated.grantUsageAccess()) openUsageAccessSettings(context)
+ usage = BankingPause.hasUsageAccess(context)
+ }) { Text(stringResource(R.string.action_allow)) }
+ }
+ paused -> Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
+ Note(stringResource(R.string.banking_paused_now), Modifier.weight(1f).padding(end = 12.dp))
+ TextButton(onClick = { BankingPause.resume(context) }) {
+ Text(stringResource(R.string.banking_turn_back_on))
+ }
+ }
+ }
+ val canPin = remember { OpenWithPauseActivity.canPin(context) }
+ for (app in remember(chosen) { describe(context, chosen) }) {
+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
+ AppIcon(app.icon)
+ Text(
+ app.label,
+ style = MaterialTheme.typography.bodyMedium,
+ modifier = Modifier.weight(1f).padding(horizontal = 12.dp),
+ )
+ if (canPin) {
+ TextButton(onClick = { OpenWithPauseActivity.pin(context, app.pkg, app.label) }) {
+ Text(stringResource(R.string.banking_shortcut))
+ }
+ }
+ }
+ }
+ if (canPin) Note(stringResource(R.string.banking_shortcut_hint))
+ }
+ }
+
+ if (picking) {
+ AppPicker(
+ initial = chosen,
+ onDone = { picked ->
+ picking = false
+ BankingPause.setApps(context, picked)
+ chosen = picked
+ // Elevated can let NectarLink see the app in front right away.
+ if (picked.isNotEmpty() && !BankingPause.hasUsageAccess(context)) {
+ Elevated.grantUsageAccess()
+ usage = BankingPause.hasUsageAccess(context)
+ }
+ },
+ onCancel = { picking = false },
+ )
+ }
+}
+
+@Composable
+private fun AppPicker(initial: Set<String>, onDone: (Set<String>) -> Unit, onCancel: () -> Unit) {
+ val context = LocalContext.current
+ val apps = remember { launchableApps(context) }
+ var selected by remember { mutableStateOf(initial) }
+ var query by remember { mutableStateOf("") }
+ val shown = apps.filter { query.isBlank() || it.label.contains(query.trim(), ignoreCase = true) }
+ AlertDialog(
+ onDismissRequest = onCancel,
+ title = { Text(stringResource(R.string.banking_pick_title)) },
+ text = {
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ OutlinedTextField(
+ value = query,
+ onValueChange = { query = it },
+ singleLine = true,
+ label = { Text(stringResource(R.string.banking_search)) },
+ modifier = Modifier.fillMaxWidth(),
+ )
+ LazyColumn(Modifier.heightIn(max = 360.dp)) {
+ items(shown, key = { it.pkg }) { app ->
+ val on = app.pkg in selected
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier
+ .fillMaxWidth()
+ .clickable { selected = if (on) selected - app.pkg else selected + app.pkg }
+ .padding(vertical = 4.dp),
+ ) {
+ Checkbox(checked = on, onCheckedChange = null)
+ AppIcon(app.icon)
+ Text(app.label, modifier = Modifier.padding(start = 12.dp))
+ }
+ }
+ }
+ }
+ },
+ confirmButton = { TextButton(onClick = { onDone(selected) }) { Text(stringResource(R.string.action_done)) } },
+ dismissButton = { TextButton(onClick = onCancel) { Text(stringResource(R.string.action_cancel)) } },
+ )
+}
+
+@Composable
+private fun AppIcon(icon: ImageBitmap?) {
+ if (icon != null) Image(icon, contentDescription = null, modifier = Modifier.size(28.dp))
+}
+
+@Composable
+private fun Note(text: String, modifier: Modifier = Modifier) {
+ Text(text, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = modifier)
+}
+
+/** Apps with a launcher icon, by name, NectarLink left out. */
+private fun launchableApps(context: Context): List<Choosable> {
+ val manager = context.packageManager
+ val launcher = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
+ @Suppress("DEPRECATION")
+ val found = manager.queryIntentActivities(launcher, 0)
+ return found.map { it.activityInfo }
+ .filter { it.packageName != context.packageName }
+ .distinctBy { it.packageName }
+ .map { info -> Choosable(info.packageName, info.loadLabel(manager).toString().trim(), iconOf(manager, info.packageName)) }
+ .sortedBy { it.label.lowercase() }
+}
+
+/** The chosen apps that are still installed, by name. */
+private fun describe(context: Context, packages: Set<String>): List<Choosable> {
+ val manager = context.packageManager
+ return packages.mapNotNull { pkg ->
+ runCatching {
+ val info = manager.getApplicationInfo(pkg, 0)
+ Choosable(pkg, manager.getApplicationLabel(info).toString(), iconOf(manager, pkg))
+ }.getOrNull()
+ }.sortedBy { it.label.lowercase() }
+}
+
+private fun iconOf(manager: PackageManager, pkg: String): ImageBitmap? =
+ runCatching { manager.getApplicationIcon(pkg).toBitmap(96, 96).asImageBitmap() }.getOrNull()
+
+private fun openUsageAccessSettings(context: Context) {
+ runCatching {
+ context.startActivity(Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
+ }
+}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt
index 153babc..c8b12b5 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt
@@ -541,6 +541,8 @@ fun SettingsScreen(
SettingRowDivider()
ElevatedAccess()
SettingRowDivider()
+ BankingPauseAccess()
+ SettingRowDivider()
DndAccess(state.dndAccess)
SettingRowDivider()
WriteSettingsAccess(state.writeSettingsAccess || state.elevated)
diff --git a/android/app/src/main/res/values-zh-rCN/strings.xml b/android/app/src/main/res/values-zh-rCN/strings.xml
index e81db07..54f6395 100644
--- a/android/app/src/main/res/values-zh-rCN/strings.xml
+++ b/android/app/src/main/res/values-zh-rCN/strings.xml
@@ -1162,4 +1162,23 @@
<string name="settings_theme_artwork_body">让应用与玻璃配色跟随播放中的媒体封面</string>
<string name="settings_wireless_debugging_active">无线调试已启用 · 剪贴板会自动同步</string>
<string name="settings_wireless_debugging_hint">允许无线调试后,剪贴板才能在后台同步;也可以在通知里点「发送剪贴板」</string>
+ <!-- Pause for banking apps -->
+ <string name="banking_title">为银行应用暂停</string>
+ <string name="banking_text">部分银行应用在开发者选项、调试或无障碍服务开启时无法打开。在这里选择这些应用:打开它们时,NectarLink会关闭这些设置,离开后再重新开启。</string>
+ <plurals name="banking_chosen">
+ <item quantity="other">已选择%1$d个应用</item>
+ </plurals>
+ <string name="banking_needs_elevated">需要先设置一次无线调试,NectarLink才能更改这些设置。</string>
+ <string name="banking_needs_usage">请允许使用情况访问权限,以便NectarLink知道银行应用何时打开。</string>
+ <string name="banking_paused_now">已为银行应用暂停。</string>
+ <string name="banking_choose">选择应用</string>
+ <string name="banking_pick_title">银行应用</string>
+ <string name="banking_search">搜索应用</string>
+ <string name="banking_shortcut">添加快捷方式</string>
+ <string name="banking_shortcut_hint">如果应用仍然无法打开,请通过它的快捷方式打开:NectarLink会先暂停,再打开它。</string>
+ <string name="banking_channel">为银行应用暂停</string>
+ <string name="banking_paused_title">已为银行应用暂停</string>
+ <string name="banking_paused_text">在你离开该应用之前,开发者选项、调试和NectarLink的无障碍服务将保持关闭。</string>
+ <string name="banking_turn_back_on">重新开启</string>
+ <string name="action_done">完成</string>
</resources>
diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml
index bc45e10..a3ef2f5 100644
--- a/android/app/src/main/res/values/strings.xml
+++ b/android/app/src/main/res/values/strings.xml
@@ -1298,6 +1298,27 @@
<string name="settings_theme_artwork_body">Sync app &amp; glass colors with playing media artwork</string>
<string name="settings_wireless_debugging_active">Active via Wireless Debugging · clipboard syncs automatically</string>
<string name="settings_wireless_debugging_hint">Allow Wireless Debugging so clipboard can sync in the background, or use Send clipboard in the notification</string>
+
+ <!-- Pause for banking apps -->
+ <string name="banking_title">Pause for banking apps</string>
+ <string name="banking_text">Some banking apps won\'t open while Developer options, debugging or an accessibility service is on. Choose them here: NectarLink turns those off while they\'re open and back on when you leave.</string>
+ <plurals name="banking_chosen">
+ <item quantity="one">%1$d app chosen</item>
+ <item quantity="other">%1$d apps chosen</item>
+ </plurals>
+ <string name="banking_needs_elevated">Needs Elevated set up once, so NectarLink can change these settings.</string>
+ <string name="banking_needs_usage">Allow usage access, so NectarLink can see when a banking app is open.</string>
+ <string name="banking_paused_now">Paused now for a banking app.</string>
+ <string name="banking_choose">Choose apps</string>
+ <string name="banking_pick_title">Banking apps</string>
+ <string name="banking_search">Search apps</string>
+ <string name="banking_shortcut">Add shortcut</string>
+ <string name="banking_shortcut_hint">If an app still refuses to open, open it from its shortcut: NectarLink pauses first, then opens it.</string>
+ <string name="banking_channel">Pause for banking apps</string>
+ <string name="banking_paused_title">Paused for a banking app</string>
+ <string name="banking_paused_text">Developer options, debugging and NectarLink\'s accessibility service are off until you leave it.</string>
+ <string name="banking_turn_back_on">Turn back on</string>
+ <string name="action_done">Done</string>
</resources>
diff --git a/android/app/src/test/kotlin/app/nectarlink/android/banking/PauseDeciderTest.kt b/android/app/src/test/kotlin/app/nectarlink/android/banking/PauseDeciderTest.kt
new file mode 100644
index 0000000..4f404fe
--- /dev/null
+++ b/android/app/src/test/kotlin/app/nectarlink/android/banking/PauseDeciderTest.kt
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package app.nectarlink.android.banking
+
+import app.nectarlink.android.banking.PauseDecider.Action
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Test
+
+class PauseDeciderTest {
+ private val bank = "com.uco.bank"
+ private val upi = "com.upi.pay"
+ private val apps = setOf(bank, upi)
+
+ @Test
+ fun pausesAsSoonAsABankingAppIsInFront() {
+ val d = PauseDecider()
+ assertNull(d.decide("com.launcher", apps, paused = false, nowMs = 0))
+ assertEquals(Action.PAUSE, d.decide(bank, apps, paused = false, nowMs = 10))
+ // Already paused: nothing more to do while it stays in front.
+ assertNull(d.decide(bank, apps, paused = true, nowMs = 1_000))
+ }
+
+ @Test
+ fun turnsBackOnOnlyAfterAnotherAppStaysInFront() {
+ val d = PauseDecider(resumeAfterMs = 3_000)
+ assertNull(d.decide("com.launcher", apps, paused = true, nowMs = 0))
+ assertNull(d.decide("com.launcher", apps, paused = true, nowMs = 2_999))
+ assertEquals(Action.RESUME, d.decide("com.launcher", apps, paused = true, nowMs = 3_000))
+ }
+
+ @Test
+ fun aQuickHopToAnotherAppAndBackKeepsThePause() {
+ val d = PauseDecider(resumeAfterMs = 3_000)
+ assertNull(d.decide("com.camera.qr", apps, paused = true, nowMs = 0))
+ // Back in the banking app before the wait is over.
+ assertNull(d.decide(bank, apps, paused = true, nowMs = 1_500))
+ // Leaving again starts the wait over.
+ assertNull(d.decide("com.camera.qr", apps, paused = true, nowMs = 2_000))
+ assertNull(d.decide("com.camera.qr", apps, paused = true, nowMs = 4_500))
+ assertEquals(Action.RESUME, d.decide("com.camera.qr", apps, paused = true, nowMs = 5_000))
+ }
+
+ @Test
+ fun movingBetweenChosenAppsKeepsThePause() {
+ val d = PauseDecider()
+ assertEquals(Action.PAUSE, d.decide(bank, apps, paused = false, nowMs = 0))
+ assertNull(d.decide(upi, apps, paused = true, nowMs = 10_000))
+ }
+
+ @Test
+ fun systemScreensOverABankingAppChangeNothing() {
+ val d = PauseDecider(resumeAfterMs = 3_000)
+ assertNull(d.decide("com.google.android.permissioncontroller", apps, paused = true, nowMs = 0))
+ assertNull(d.decide("com.android.systemui", apps, paused = true, nowMs = 60_000))
+ assertNull(d.decide(null, apps, paused = true, nowMs = 120_000))
+ }
+
+ @Test
+ fun nothingHappensWhenNotPausedAndNoBankingAppIsInFront() {
+ val d = PauseDecider()
+ assertNull(d.decide("com.launcher", apps, paused = false, nowMs = 0))
+ assertNull(d.decide("com.launcher", emptySet(), paused = false, nowMs = 60_000))
+ }
+}
diff --git a/docs/guide/troubleshooting.md b/docs/guide/troubleshooting.md
index c828bf8..c1d359c 100644
--- a/docs/guide/troubleshooting.md
+++ b/docs/guide/troubleshooting.md
@@ -59,6 +59,18 @@ On Android 13 and newer, if you install an APK downloaded from a browser or GitH
- If you turn the master **Developer options** switch off in Android Settings, Android stops Wireless Debugging and terminates the `Elevated` shell helper. Keep **Developer options** turned on if you use `Elevated` features. (When you reboot your phone or reconnect to Wi-Fi with Developer options on, NectarLink automatically re-enables Wireless Debugging and restarts `Elevated` by itself.)
+### A Banking App Won't Open
+
+Many banking apps refuse to run while **Developer options**, USB or Wireless Debugging, or an accessibility service is on, all of which `Elevated` and Assist use. NectarLink can switch them off while those apps are open:
+
+1. Open **Settings › Permissions › Control from your PC › Pause for banking apps** and tap **Choose apps**.
+2. Pick your banking and payment apps. NectarLink needs `Elevated` set up once, and usage access (tap **Allow** if it asks), to see which app is open.
+3. Open a banking app as usual. NectarLink turns off Developer options, debugging and its accessibility service while it's open, and turns back on exactly what was on when you leave. A notification shows while it's paused, with **Turn back on**.
+
+If an app checks before NectarLink notices it, tap **Add shortcut** next to it and open it from that home screen shortcut: NectarLink pauses first, then opens the app.
+
+Some banking apps also refuse to run on a phone that was ever rooted (on Samsung phones, a tripped Knox flag). NectarLink can't change that.
+
## 5. Troubleshooting USB Auto-Pair and `On USB` Transport
If plugging your phone into your PC with a USB cable does not trigger USB auto-pair or switch your connection to `On USB`: