diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..11aed02 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,4 @@ +* text=auto +gradlew text eol=lf +*.bat text eol=crlf +*.jar binary diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..fbbeb67 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,33 @@ +name: CI + +on: + pull_request: + push: + branches: [master] + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: 21 + + - uses: gradle/actions/setup-gradle@v5 + + - name: Unit tests, lint and debug build + run: ./gradlew testDebugUnitTest lintDebug assembleDebug + + - name: Upload test and lint reports + if: failure() + uses: actions/upload-artifact@v4 + with: + name: reports + path: app/build/reports/ diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..72451ff --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,53 @@ +name: Release + +# Push a version tag to publish a signed APK, for example: +# git tag v1.2.0 && git push origin v1.2.0 +on: + push: + tags: ["v*.*.*"] + +permissions: + contents: write + +jobs: + release: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: 21 + + - uses: gradle/actions/setup-gradle@v5 + + - name: Decode release keystore + env: + KEYSTORE_BASE64: ${{ secrets.RELEASE_KEYSTORE_BASE64 }} + run: | + if [ -z "$KEYSTORE_BASE64" ]; then + echo "::error::Secret RELEASE_KEYSTORE_BASE64 is not set. See README, section Releases." + exit 1 + fi + echo "$KEYSTORE_BASE64" | base64 --decode > "$RUNNER_TEMP/release.jks" + + - name: Test and build signed APK + env: + SIGNING_STORE_FILE: ${{ runner.temp }}/release.jks + SIGNING_STORE_PASSWORD: ${{ secrets.RELEASE_KEYSTORE_PASSWORD }} + SIGNING_KEY_ALIAS: ${{ vars.RELEASE_KEY_ALIAS || 'rrgmc' }} + SIGNING_KEY_PASSWORD: ${{ secrets.RELEASE_KEYSTORE_PASSWORD }} + run: ./gradlew testDebugUnitTest lintDebug assembleRelease -PappVersion="${GITHUB_REF_NAME#v}" + + - name: Publish GitHub release + env: + GH_TOKEN: ${{ github.token }} + run: | + apk="android-dev-settings-${GITHUB_REF_NAME}.apk" + cp app/build/outputs/apk/release/app-release.apk "$apk" + gh release create "$GITHUB_REF_NAME" "$apk" --title "$GITHUB_REF_NAME" --generate-notes + + - name: Remove keystore + if: always() + run: rm -f "$RUNNER_TEMP/release.jks" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..919975f --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +.gradle/ +build/ +local.properties +.idea/ +*.iml +.kotlin/ +captures/ +.cxx/ diff --git a/README.md b/README.md index 43c3621..388d0bf 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,110 @@ -# android-dev-settings -android-dev-settings +# Android Dev Settings + +An Android app that toggles the developer settings I use most, without opening Developer options: + +- USB debugging +- Wireless debugging +- Stay awake while charging (AC, USB and wireless) +- Keep screen on for a chosen time, charging or not + +The app is for my own phones. It is not published on the Play Store. It needs Android 11 (API 30) or later. + +## Build + +Requirements: JDK 17 or later, and the Android SDK with platform 36. Put the SDK path in +`local.properties` (`sdk.dir=...`) or in the `ANDROID_HOME` environment variable. + +```bash +./gradlew assembleDebug +``` + +The APK is `app/build/outputs/apk/debug/app-debug.apk`. Install it with: + +```bash +adb install -r app/build/outputs/apk/debug/app-debug.apk +``` + +Run the unit tests and lint with: + +```bash +./gradlew testDebugUnitTest lintDebug +``` + +## Grant the permission + +Changing these settings needs `android.permission.WRITE_SECURE_SETTINGS`. Only a computer can grant it, and +only once per installation: + +1. Turn on USB debugging in Developer options and connect the phone to the computer. +2. Run: + + ```bash + adb shell pm grant com.rangelreale.devsettings android.permission.WRITE_SECURE_SETTINGS + ``` + +Until the permission is granted, the main screen shows a setup card with this command and a copy button, and every +switch stays disabled. The app notices the grant within a few seconds. It needs neither root nor Shizuku. + +Developer options must be on for the settings to have effect. When they are off, the main screen explains how to +turn them on: open About phone and tap Build number seven times. + +## Main screen + +Each row shows the setting, its current value and a switch. Values come from the system on every resume and +through a content observer, so changes made in system Settings appear at once. + +- Turning off USB or wireless debugging asks for confirmation, because a connected computer loses its connection. +- When wireless debugging is on, the screen shows the phone's address and port for `adb connect`, with a copy + button. The port is found through the `service.adb.tls.port` property or, failing that, mDNS. +- The first time wireless debugging is turned on for a Wi-Fi network, Android asks whether to allow that network. +- "Open wireless debugging (pairing)" opens Developer options with the wireless debugging row highlighted. Tap the + row title to reach pairing. Android has no public intent for the pairing screen itself. +- "Open Developer options" opens the system Developer options screen. + +## Quick Settings tiles + +Add the tiles from the Quick Settings edit screen. Every tile shows the real system state, and a long press opens +the app. Without the permission, a tile shows "Setup needed" and a tap opens the app on the setup card. (Android +does not deliver taps to tiles in the unavailable state, so these tiles stay inactive instead.) + +| Tile | Tap | +| --- | --- | +| USB debugging | Turns USB debugging on or off. On a locked phone, it asks to unlock first. | +| Wireless debugging | Turns wireless debugging on or off. On a locked phone, it asks to unlock first. | +| Stay awake | Turns stay awake while charging on (AC, USB and wireless) or off. | +| Keep screen on | Moves to the next step: 5 min, 15 min, 30 min, 1 hour, until stopped, off. Each step restarts the countdown. The subtitle shows the time left. | + +Tiles do not ask for confirmation. + +## Keep screen on + +A foreground service holds a screen wake lock. Its ongoing notification counts down the time left and has a Stop +action. On Android 13 and later, the app asks for notification permission the first time; without it, the screen +still stays on but the notification is hidden. The power button still turns the screen off. + +## Releases + +CI runs on every pull request and every push to `master`: unit tests, lint and a debug build +(`.github/workflows/ci.yml`). + +Pushing a tag such as `v1.2.0` runs `.github/workflows/release.yml`. It tests, builds an APK signed with the +release key, and publishes it as a GitHub release. The version name comes from the tag (`1.2.0`) and the version +code is `major * 10000 + minor * 100 + patch`. + +```bash +git tag v1.2.0 +git push origin v1.2.0 +``` + +The release workflow needs two repository secrets: + +| Secret | Value | +| --- | --- | +| `RELEASE_KEYSTORE_BASE64` | The keystore file, base64-encoded. | +| `RELEASE_KEYSTORE_PASSWORD` | The keystore password. It is also used as the key password. | + +The key alias defaults to `rrgmc`. Set the repository variable `RELEASE_KEY_ALIAS` to use another one. + +To build a signed release locally, set `SIGNING_STORE_FILE`, `SIGNING_STORE_PASSWORD`, `SIGNING_KEY_ALIAS` and +`SIGNING_KEY_PASSWORD`, then run `./gradlew assembleRelease -PappVersion=1.2.0`. Without these variables, release +builds are signed with the debug key. diff --git a/app/build.gradle.kts b/app/build.gradle.kts new file mode 100644 index 0000000..d84ee3c --- /dev/null +++ b/app/build.gradle.kts @@ -0,0 +1,83 @@ +import org.jetbrains.kotlin.gradle.dsl.JvmTarget + +plugins { + alias(libs.plugins.android.application) + alias(libs.plugins.kotlin.android) + alias(libs.plugins.kotlin.compose) +} + +// Release CI passes the tag without its "v" prefix: -PappVersion=1.2.3 +val appVersion = providers.gradleProperty("appVersion").orNull ?: "0.1.0" +val appVersionCode = appVersion.substringBefore('-').split('.').map { it.toInt() } + .let { (major, minor, patch) -> major * 10_000 + minor * 100 + patch } + +// Release signing comes from environment variables. Without them, release builds use the debug key. +val releaseStoreFile: String? = System.getenv("SIGNING_STORE_FILE") + +android { + namespace = "com.rangelreale.devsettings" + compileSdk = 36 + + defaultConfig { + applicationId = "com.rangelreale.devsettings" + minSdk = 30 + targetSdk = 36 + versionCode = appVersionCode + versionName = appVersion + } + + signingConfigs { + if (releaseStoreFile != null) { + create("release") { + storeFile = file(releaseStoreFile) + storePassword = System.getenv("SIGNING_STORE_PASSWORD") + keyAlias = System.getenv("SIGNING_KEY_ALIAS") + keyPassword = System.getenv("SIGNING_KEY_PASSWORD") + } + } + } + + buildTypes { + release { + isMinifyEnabled = false + signingConfig = signingConfigs.findByName("release") ?: signingConfigs.getByName("debug") + } + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + buildFeatures { + compose = true + } + + lint { + // targetSdk 36 and the tool and library versions are pinned on purpose; newer ones need compileSdk 37. + // These checks also look up versions online, so their result would change as new releases appear. + disable += setOf("OldTargetApi", "GradleDependency", "AndroidGradlePluginVersion", "NewerVersionAvailable") + warningsAsErrors = true + } +} + +kotlin { + compilerOptions { + jvmTarget.set(JvmTarget.JVM_17) + } +} + +dependencies { + implementation(libs.androidx.core.ktx) + implementation(libs.androidx.lifecycle.runtime.ktx) + implementation(libs.androidx.lifecycle.runtime.compose) + implementation(libs.androidx.activity.compose) + implementation(libs.kotlinx.coroutines.android) + implementation(platform(libs.androidx.compose.bom)) + implementation(libs.androidx.compose.ui) + implementation(libs.androidx.compose.ui.tooling.preview) + implementation(libs.androidx.compose.material3) + debugImplementation(libs.androidx.compose.ui.tooling) + + testImplementation(libs.junit) +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..246cae5 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,103 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/java/com/rangelreale/devsettings/MainActivity.kt b/app/src/main/java/com/rangelreale/devsettings/MainActivity.kt new file mode 100644 index 0000000..79c56a1 --- /dev/null +++ b/app/src/main/java/com/rangelreale/devsettings/MainActivity.kt @@ -0,0 +1,27 @@ +package com.rangelreale.devsettings + +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import com.rangelreale.devsettings.data.AndroidSettingsStore +import com.rangelreale.devsettings.data.DevSettingsRepository +import com.rangelreale.devsettings.ui.DevSettingsTheme +import com.rangelreale.devsettings.ui.MainScreen + +/** + * The main screen. Tiles open it on long press, and on tap when the permission is missing. + * The setup card sits at the top of the screen whenever the permission is missing. + */ +class MainActivity : ComponentActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enableEdgeToEdge() + val repository = DevSettingsRepository(AndroidSettingsStore(applicationContext)) + setContent { + DevSettingsTheme { + MainScreen(repository) + } + } + } +} diff --git a/app/src/main/java/com/rangelreale/devsettings/SystemScreens.kt b/app/src/main/java/com/rangelreale/devsettings/SystemScreens.kt new file mode 100644 index 0000000..eb3c975 --- /dev/null +++ b/app/src/main/java/com/rangelreale/devsettings/SystemScreens.kt @@ -0,0 +1,43 @@ +package com.rangelreale.devsettings + +import android.content.ActivityNotFoundException +import android.content.Context +import android.content.Intent +import android.os.Bundle +import android.provider.Settings + +/** Intents into the system Settings app. */ +object SystemScreens { + + /** Settings key of the wireless debugging row inside Developer options. */ + private const val WIRELESS_DEBUGGING_PREF_KEY = "toggle_adb_wireless" + private const val EXTRA_FRAGMENT_ARG_KEY = ":settings:fragment_args_key" + private const val EXTRA_SHOW_FRAGMENT_ARGUMENTS = ":settings:show_fragment_args" + + fun openDeveloperOptions(context: Context) = + launch(context, Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS)) + + /** + * Android has no public intent for the wireless debugging screen. This opens Developer options + * scrolled to the wireless debugging row, highlighted. Tap the row title to reach pairing. + */ + fun openWirelessDebugging(context: Context) { + val intent = Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS) + .putExtra(EXTRA_FRAGMENT_ARG_KEY, WIRELESS_DEBUGGING_PREF_KEY) + .putExtra( + EXTRA_SHOW_FRAGMENT_ARGUMENTS, + Bundle().apply { putString(EXTRA_FRAGMENT_ARG_KEY, WIRELESS_DEBUGGING_PREF_KEY) }, + ) + launch(context, intent) + } + + fun openAboutPhone(context: Context) = launch(context, Intent(Settings.ACTION_DEVICE_INFO_SETTINGS)) + + private fun launch(context: Context, intent: Intent) { + try { + context.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) + } catch (e: ActivityNotFoundException) { + context.startActivity(Intent(Settings.ACTION_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) + } + } +} diff --git a/app/src/main/java/com/rangelreale/devsettings/data/AndroidSettingsStore.kt b/app/src/main/java/com/rangelreale/devsettings/data/AndroidSettingsStore.kt new file mode 100644 index 0000000..1b74510 --- /dev/null +++ b/app/src/main/java/com/rangelreale/devsettings/data/AndroidSettingsStore.kt @@ -0,0 +1,31 @@ +package com.rangelreale.devsettings.data + +import android.Manifest +import android.content.Context +import android.content.pm.PackageManager +import android.provider.Settings + +/** [SettingsStore] backed by the real `Settings.Global` table. */ +class AndroidSettingsStore(context: Context) : SettingsStore { + private val context = context.applicationContext + + override fun getGlobalInt(key: String, default: Int): Int = + try { + Settings.Global.getInt(context.contentResolver, key, default) + } catch (e: SecurityException) { + default + } + + override fun putGlobalInt(key: String, value: Int): Boolean = + try { + Settings.Global.putInt(context.contentResolver, key, value) + } catch (e: SecurityException) { + false + } catch (e: IllegalArgumentException) { + false + } + + override fun hasWriteSecureSettings(): Boolean = + context.checkSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS) == + PackageManager.PERMISSION_GRANTED +} diff --git a/app/src/main/java/com/rangelreale/devsettings/data/DevSetting.kt b/app/src/main/java/com/rangelreale/devsettings/data/DevSetting.kt new file mode 100644 index 0000000..b3fd19b --- /dev/null +++ b/app/src/main/java/com/rangelreale/devsettings/data/DevSetting.kt @@ -0,0 +1,36 @@ +package com.rangelreale.devsettings.data + +/** + * A developer setting stored as an integer in `Settings.Global`. + * + * The keys are literal strings so the logic runs in plain JVM unit tests. + * They match the `Settings.Global` constants named in each comment. + */ +/** + * [verifyWrite] is false when Android may apply the value later. Turning on wireless debugging + * first shows a system dialog asking to allow the current network, so the value stays 0 until then. + */ +enum class DevSetting(val key: String, val onValue: Int, val verifyWrite: Boolean = true) { + /** `Settings.Global.ADB_ENABLED`. */ + USB_DEBUGGING("adb_enabled", 1), + + /** `adb_wifi_enabled` (hidden constant `Settings.Global.ADB_WIFI_ENABLED`). */ + WIRELESS_DEBUGGING("adb_wifi_enabled", 1, verifyWrite = false), + + /** + * `Settings.Global.STAY_ON_WHILE_PLUGGED_IN`. The value is a bit mask: + * 1 = AC, 2 = USB, 4 = wireless. "On" sets all three (7). + */ + STAY_AWAKE("stay_on_while_plugged_in", 7), +} + +object GlobalKeys { + /** `Settings.Global.DEVELOPMENT_SETTINGS_ENABLED`. */ + const val DEVELOPMENT_SETTINGS_ENABLED = "development_settings_enabled" +} + +const val WRITE_SECURE_SETTINGS = "android.permission.WRITE_SECURE_SETTINGS" + +/** The command that grants the permission from a computer. */ +fun grantCommand(packageName: String): String = + "adb shell pm grant $packageName $WRITE_SECURE_SETTINGS" diff --git a/app/src/main/java/com/rangelreale/devsettings/data/DevSettingsRepository.kt b/app/src/main/java/com/rangelreale/devsettings/data/DevSettingsRepository.kt new file mode 100644 index 0000000..f5500df --- /dev/null +++ b/app/src/main/java/com/rangelreale/devsettings/data/DevSettingsRepository.kt @@ -0,0 +1,25 @@ +package com.rangelreale.devsettings.data + +enum class WriteResult { SUCCESS, MISSING_PERMISSION, FAILED } + +/** Reads and writes the developer settings. Every read goes to the store; nothing is cached. */ +class DevSettingsRepository(private val store: SettingsStore) { + + fun hasPermission(): Boolean = store.hasWriteSecureSettings() + + fun developerOptionsEnabled(): Boolean = + store.getGlobalInt(GlobalKeys.DEVELOPMENT_SETTINGS_ENABLED, 0) != 0 + + /** Any non-zero value counts as on. For stay awake, this includes partial masks such as 1 (AC only). */ + fun isEnabled(setting: DevSetting): Boolean = store.getGlobalInt(setting.key, 0) != 0 + + fun setEnabled(setting: DevSetting, enabled: Boolean): WriteResult { + if (!hasPermission()) return WriteResult.MISSING_PERMISSION + val value = if (enabled) setting.onValue else 0 + if (!store.putGlobalInt(setting.key, value)) return WriteResult.FAILED + if (!setting.verifyWrite) return WriteResult.SUCCESS + return if (store.getGlobalInt(setting.key, -1) == value) WriteResult.SUCCESS else WriteResult.FAILED + } + + fun toggle(setting: DevSetting): WriteResult = setEnabled(setting, !isEnabled(setting)) +} diff --git a/app/src/main/java/com/rangelreale/devsettings/data/SettingsStore.kt b/app/src/main/java/com/rangelreale/devsettings/data/SettingsStore.kt new file mode 100644 index 0000000..615b945 --- /dev/null +++ b/app/src/main/java/com/rangelreale/devsettings/data/SettingsStore.kt @@ -0,0 +1,17 @@ +package com.rangelreale.devsettings.data + +/** + * Minimal view of `Settings.Global` and the permission check. + * + * The production implementation is [AndroidSettingsStore]. Unit tests use a fake. + */ +interface SettingsStore { + /** Returns the integer value of a global setting, or [default] when it is missing or unreadable. */ + fun getGlobalInt(key: String, default: Int): Int + + /** Writes a global setting. Returns false when the system rejects the write. */ + fun putGlobalInt(key: String, value: Int): Boolean + + /** True when the app holds `android.permission.WRITE_SECURE_SETTINGS`. */ + fun hasWriteSecureSettings(): Boolean +} diff --git a/app/src/main/java/com/rangelreale/devsettings/data/WirelessDebugInfo.kt b/app/src/main/java/com/rangelreale/devsettings/data/WirelessDebugInfo.kt new file mode 100644 index 0000000..66cf01b --- /dev/null +++ b/app/src/main/java/com/rangelreale/devsettings/data/WirelessDebugInfo.kt @@ -0,0 +1,106 @@ +package com.rangelreale.devsettings.data + +import android.content.Context +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import android.net.nsd.NsdManager +import android.net.nsd.NsdServiceInfo +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.suspendCancellableCoroutine +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull +import java.net.Inet4Address +import kotlin.coroutines.resume + +/** Finds the phone's Wi-Fi address and the port that wireless debugging listens on. */ +object WirelessDebugInfo { + + /** mDNS service type that adbd advertises while wireless debugging is on. */ + private const val ADB_TLS_SERVICE = "_adb-tls-connect._tcp" + + /** IPv4 address of the current Wi-Fi network, or null when not on Wi-Fi. */ + fun wifiIpAddress(context: Context): String? { + val cm = context.getSystemService(ConnectivityManager::class.java) ?: return null + val network = cm.activeNetwork ?: return null + val caps = cm.getNetworkCapabilities(network) ?: return null + if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) return null + return cm.getLinkProperties(network)?.linkAddresses + ?.map { it.address } + ?.firstOrNull { it is Inet4Address && !it.isLoopbackAddress } + ?.hostAddress + } + + /** + * Port of the wireless debugging service on this phone, or null when it cannot be found. + * Reads the adbd system property first, then falls back to mDNS discovery. + */ + suspend fun findPort(context: Context, ipAddress: String): Int? = + readPortProperty() ?: discoverPort(context, ipAddress) + + private suspend fun readPortProperty(): Int? = withContext(Dispatchers.IO) { + try { + val process = ProcessBuilder("getprop", "service.adb.tls.port").start() + val output = process.inputStream.bufferedReader().use { it.readText() }.trim() + process.waitFor() + output.toIntOrNull()?.takeIf { it > 0 } + } catch (e: Exception) { + null + } + } + + private suspend fun discoverPort(context: Context, ipAddress: String): Int? { + val nsd = context.getSystemService(NsdManager::class.java) ?: return null + val found = Channel(Channel.UNLIMITED) + val listener = object : NsdManager.DiscoveryListener { + override fun onServiceFound(info: NsdServiceInfo) { + found.trySend(info) + } + + override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) { + found.close() + } + + override fun onDiscoveryStarted(serviceType: String) = Unit + override fun onServiceLost(info: NsdServiceInfo) = Unit + override fun onDiscoveryStopped(serviceType: String) = Unit + override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) = Unit + } + + nsd.discoverServices(ADB_TLS_SERVICE, NsdManager.PROTOCOL_DNS_SD, listener) + return try { + withTimeoutOrNull(5_000) { + // Other devices on the network may advertise the same service. Keep the one on this phone. + for (info in found) { + val resolved = resolve(nsd, info) ?: continue + @Suppress("DEPRECATION") + if (resolved.host?.hostAddress == ipAddress) return@withTimeoutOrNull resolved.port + } + null + } + } finally { + try { + nsd.stopServiceDiscovery(listener) + } catch (e: IllegalArgumentException) { + // Discovery never started. + } + } + } + + @Suppress("DEPRECATION") // resolveService still works and keeps the code the same on API 30 to 36. + private suspend fun resolve(nsd: NsdManager, info: NsdServiceInfo): NsdServiceInfo? = + suspendCancellableCoroutine { cont -> + nsd.resolveService( + info, + object : NsdManager.ResolveListener { + override fun onServiceResolved(resolved: NsdServiceInfo) { + if (cont.isActive) cont.resume(resolved) + } + + override fun onResolveFailed(failed: NsdServiceInfo, errorCode: Int) { + if (cont.isActive) cont.resume(null) + } + }, + ) + } +} diff --git a/app/src/main/java/com/rangelreale/devsettings/keepon/DurationLabels.kt b/app/src/main/java/com/rangelreale/devsettings/keepon/DurationLabels.kt new file mode 100644 index 0000000..c04bfc6 --- /dev/null +++ b/app/src/main/java/com/rangelreale/devsettings/keepon/DurationLabels.kt @@ -0,0 +1,14 @@ +package com.rangelreale.devsettings.keepon + +import androidx.annotation.StringRes +import com.rangelreale.devsettings.R + +@get:StringRes +val KeepScreenOnDuration.labelRes: Int + get() = when (this) { + KeepScreenOnDuration.MIN_5 -> R.string.duration_5_min + KeepScreenOnDuration.MIN_15 -> R.string.duration_15_min + KeepScreenOnDuration.MIN_30 -> R.string.duration_30_min + KeepScreenOnDuration.HOUR_1 -> R.string.duration_1_hour + KeepScreenOnDuration.INDEFINITE -> R.string.duration_indefinite + } diff --git a/app/src/main/java/com/rangelreale/devsettings/keepon/KeepScreenOnDuration.kt b/app/src/main/java/com/rangelreale/devsettings/keepon/KeepScreenOnDuration.kt new file mode 100644 index 0000000..b64cff6 --- /dev/null +++ b/app/src/main/java/com/rangelreale/devsettings/keepon/KeepScreenOnDuration.kt @@ -0,0 +1,41 @@ +package com.rangelreale.devsettings.keepon + +import java.util.concurrent.TimeUnit + +/** The fixed durations offered for "Keep screen on". [minutes] is null for "indefinitely". */ +enum class KeepScreenOnDuration(val minutes: Long?) { + MIN_5(5), + MIN_15(15), + MIN_30(30), + HOUR_1(60), + INDEFINITE(null); + + val millis: Long? get() = minutes?.let { TimeUnit.MINUTES.toMillis(it) } + + companion object { + /** + * The next step of the tile cycle: off, 5 min, 15 min, 30 min, 1 hour, indefinitely, off. + * Null means off. + */ + fun next(current: KeepScreenOnDuration?): KeepScreenOnDuration? = when (current) { + null -> entries.first() + entries.last() -> null + else -> entries[current.ordinal + 1] + } + } +} + +/** A running keep-screen-on session. [endsAtMillis] is wall-clock time, null when indefinite. */ +data class KeepScreenOnStatus(val duration: KeepScreenOnDuration, val endsAtMillis: Long?) { + fun remainingMillis(nowMillis: Long): Long? = endsAtMillis?.let { (it - nowMillis).coerceAtLeast(0) } +} + +/** Formats a remaining time as `h:mm:ss` or `m:ss`. */ +fun formatRemaining(millis: Long): String { + val totalSeconds = (millis + 999) / 1000 + val hours = totalSeconds / 3600 + val minutes = (totalSeconds % 3600) / 60 + val seconds = totalSeconds % 60 + return if (hours > 0) "%d:%02d:%02d".format(hours, minutes, seconds) + else "%d:%02d".format(minutes, seconds) +} diff --git a/app/src/main/java/com/rangelreale/devsettings/keepon/KeepScreenOnService.kt b/app/src/main/java/com/rangelreale/devsettings/keepon/KeepScreenOnService.kt new file mode 100644 index 0000000..f7d8eb4 --- /dev/null +++ b/app/src/main/java/com/rangelreale/devsettings/keepon/KeepScreenOnService.kt @@ -0,0 +1,187 @@ +package com.rangelreale.devsettings.keepon + +import android.annotation.SuppressLint +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.app.Service +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.content.pm.ServiceInfo +import android.os.Build +import android.os.Handler +import android.os.IBinder +import android.os.Looper +import android.os.PowerManager +import android.service.quicksettings.TileService +import androidx.core.app.ServiceCompat +import androidx.core.content.ContextCompat +import com.rangelreale.devsettings.MainActivity +import com.rangelreale.devsettings.R +import com.rangelreale.devsettings.tiles.KeepScreenOnTileService + +/** + * Holds a screen wake lock for a chosen duration, with an ongoing notification + * that counts down and offers a Stop action. + */ +class KeepScreenOnService : Service() { + + private val handler = Handler(Looper.getMainLooper()) + private var wakeLock: PowerManager.WakeLock? = null + private val stopRunnable = Runnable { stopSelf() } + + override fun onBind(intent: Intent?): IBinder? = null + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + val duration = intent?.getStringExtra(EXTRA_DURATION) + ?.let { name -> KeepScreenOnDuration.entries.firstOrNull { it.name == name } } + if (intent?.action == ACTION_STOP || duration == null) { + stopSelf() + return START_NOT_STICKY + } + + val endsAt = duration.millis?.let { System.currentTimeMillis() + it } + val status = KeepScreenOnStatus(duration, endsAt) + + ServiceCompat.startForeground( + this, + NOTIFICATION_ID, + buildNotification(status), + // The specialUse type exists from Android 14. Earlier versions take no type here. + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { + ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE + } else { + 0 + }, + ) + + acquireWakeLock(duration.millis) + handler.removeCallbacks(stopRunnable) + duration.millis?.let { handler.postDelayed(stopRunnable, it) } + + KeepScreenOnState.set(status) + refreshTile() + return START_NOT_STICKY + } + + override fun onDestroy() { + handler.removeCallbacks(stopRunnable) + releaseWakeLock() + KeepScreenOnState.set(null) + refreshTile() + super.onDestroy() + } + + // SCREEN_BRIGHT_WAKE_LOCK is the only way to hold the screen on from a service. + // "Indefinitely" deliberately holds the lock with no timeout until the user stops it. + @Suppress("DEPRECATION") + @SuppressLint("WakelockTimeout") + private fun acquireWakeLock(timeoutMillis: Long?) { + releaseWakeLock() + val pm = getSystemService(PowerManager::class.java) + val lock = pm.newWakeLock( + PowerManager.SCREEN_BRIGHT_WAKE_LOCK or PowerManager.ON_AFTER_RELEASE, + "DevSettings:KeepScreenOn", + ) + lock.setReferenceCounted(false) + // The timeout is a safety net in case the stop callback never runs. + if (timeoutMillis != null) lock.acquire(timeoutMillis) else lock.acquire() + wakeLock = lock + } + + private fun releaseWakeLock() { + wakeLock?.let { if (it.isHeld) it.release() } + wakeLock = null + } + + private fun buildNotification(status: KeepScreenOnStatus): Notification { + val manager = getSystemService(NotificationManager::class.java) + manager.createNotificationChannel( + NotificationChannel( + CHANNEL_ID, + getString(R.string.notification_channel), + NotificationManager.IMPORTANCE_LOW, + ), + ) + + val openApp = PendingIntent.getActivity( + this, + 0, + Intent(this, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), + PendingIntent.FLAG_IMMUTABLE, + ) + val stop = PendingIntent.getService( + this, + 1, + Intent(this, KeepScreenOnService::class.java).setAction(ACTION_STOP), + PendingIntent.FLAG_IMMUTABLE, + ) + + val builder = Notification.Builder(this, CHANNEL_ID) + .setSmallIcon(R.drawable.ic_screen) + .setContentTitle(getString(R.string.notification_title)) + .setOngoing(true) + .setOnlyAlertOnce(true) + .setContentIntent(openApp) + .addAction( + Notification.Action.Builder( + android.graphics.drawable.Icon.createWithResource(this, R.drawable.ic_stop), + getString(R.string.stop), + stop, + ).build(), + ) + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + // Show the notification at once instead of after the default 10-second delay. + builder.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE) + } + if (status.endsAtMillis != null) { + // The system renders a live countdown; no per-second updates are needed. + builder.setWhen(status.endsAtMillis) + .setShowWhen(true) + .setUsesChronometer(true) + .setChronometerCountDown(true) + } else { + builder.setContentText(getString(R.string.notification_indefinite)) + .setShowWhen(false) + } + return builder.build() + } + + private fun refreshTile() { + TileService.requestListeningState( + this, + ComponentName(this, KeepScreenOnTileService::class.java), + ) + } + + companion object { + private const val CHANNEL_ID = "keep_screen_on" + private const val NOTIFICATION_ID = 1 + private const val ACTION_START = "com.rangelreale.devsettings.action.KEEP_SCREEN_ON_START" + private const val ACTION_STOP = "com.rangelreale.devsettings.action.KEEP_SCREEN_ON_STOP" + private const val EXTRA_DURATION = "duration" + + /** + * Starts or restarts the service with [duration]. The countdown starts now. + * Throws when Android refuses to start a foreground service from the caller's state. + */ + fun start(context: Context, duration: KeepScreenOnDuration) { + val intent = Intent(context, KeepScreenOnService::class.java) + .setAction(ACTION_START) + .putExtra(EXTRA_DURATION, duration.name) + ContextCompat.startForegroundService(context, intent) + } + + fun stop(context: Context) { + context.stopService(Intent(context, KeepScreenOnService::class.java)) + } + + /** Starts [duration], or stops the service when [duration] is null. */ + fun apply(context: Context, duration: KeepScreenOnDuration?) { + if (duration == null) stop(context) else start(context, duration) + } + } +} diff --git a/app/src/main/java/com/rangelreale/devsettings/keepon/KeepScreenOnState.kt b/app/src/main/java/com/rangelreale/devsettings/keepon/KeepScreenOnState.kt new file mode 100644 index 0000000..9c4d3a3 --- /dev/null +++ b/app/src/main/java/com/rangelreale/devsettings/keepon/KeepScreenOnState.kt @@ -0,0 +1,15 @@ +package com.rangelreale.devsettings.keepon + +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow + +/** Live state of [KeepScreenOnService]. Null when the service is not running. */ +object KeepScreenOnState { + private val mutable = MutableStateFlow(null) + val status: StateFlow = mutable.asStateFlow() + + internal fun set(value: KeepScreenOnStatus?) { + mutable.value = value + } +} diff --git a/app/src/main/java/com/rangelreale/devsettings/tiles/BaseTileService.kt b/app/src/main/java/com/rangelreale/devsettings/tiles/BaseTileService.kt new file mode 100644 index 0000000..78bc9f8 --- /dev/null +++ b/app/src/main/java/com/rangelreale/devsettings/tiles/BaseTileService.kt @@ -0,0 +1,109 @@ +package com.rangelreale.devsettings.tiles + +import android.annotation.SuppressLint +import android.app.PendingIntent +import android.content.Intent +import android.database.ContentObserver +import android.os.Build +import android.os.Handler +import android.os.Looper +import android.provider.Settings +import android.service.quicksettings.Tile +import android.service.quicksettings.TileService +import com.rangelreale.devsettings.MainActivity +import com.rangelreale.devsettings.R +import com.rangelreale.devsettings.data.AndroidSettingsStore +import com.rangelreale.devsettings.data.DevSettingsRepository +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.MainScope +import kotlinx.coroutines.cancel + +/** + * Shared tile behaviour. + * + * Without the permission, the tile shows "Setup needed" and a tap opens the app on the setup card. + * `Tile.STATE_UNAVAILABLE` would grey the tile out, but Android does not deliver taps to + * unavailable tiles, so the tile uses the inactive state with a subtitle instead. + * + * Long press opens the app through the `QS_TILE_PREFERENCES` intent filter on [MainActivity]. + */ +abstract class BaseTileService : TileService() { + + protected val repository by lazy { DevSettingsRepository(AndroidSettingsStore(applicationContext)) } + + /** `Settings.Global` keys whose changes refresh the tile while it is visible. */ + protected open val observedKeys: List = emptyList() + + private var scope: CoroutineScope? = null + + private val observer = object : ContentObserver(Handler(Looper.getMainLooper())) { + override fun onChange(selfChange: Boolean) = updateTile() + } + + override fun onStartListening() { + super.onStartListening() + observedKeys.forEach { + contentResolver.registerContentObserver(Settings.Global.getUriFor(it), false, observer) + } + scope = MainScope().also { onListening(it) } + updateTile() + } + + override fun onStopListening() { + contentResolver.unregisterContentObserver(observer) + scope?.cancel() + scope = null + super.onStopListening() + } + + override fun onClick() { + super.onClick() + if (!repository.hasPermission()) { + openApp() + return + } + onToggle() + updateTile() + } + + /** Called while the tile is visible, for subclasses that observe more than settings. */ + protected open fun onListening(scope: CoroutineScope) = Unit + + /** Toggles the setting. Called only when the permission is held. */ + protected abstract fun onToggle() + + /** Sets state, subtitle and description for a tile whose permission is held. */ + protected abstract fun render(tile: Tile) + + protected fun updateTile() { + val tile = qsTile ?: return + if (repository.hasPermission()) { + render(tile) + } else { + tile.state = Tile.STATE_INACTIVE + tile.subtitle = getString(R.string.tile_setup_needed) + tile.stateDescription = getString(R.string.tile_setup_needed) + } + tile.updateTile() + } + + protected fun renderOnOff(tile: Tile, on: Boolean, onSubtitle: String = getString(R.string.status_on)) { + tile.state = if (on) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE + tile.subtitle = if (on) onSubtitle else getString(R.string.status_off) + tile.stateDescription = tile.subtitle + } + + @SuppressLint("StartActivityAndCollapseDeprecated") + protected fun openApp() { + val intent = Intent(this, MainActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { + startActivityAndCollapse( + PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE), + ) + } else { + @Suppress("DEPRECATION") + startActivityAndCollapse(intent) + } + } +} diff --git a/app/src/main/java/com/rangelreale/devsettings/tiles/KeepScreenOnTileService.kt b/app/src/main/java/com/rangelreale/devsettings/tiles/KeepScreenOnTileService.kt new file mode 100644 index 0000000..7ed20ec --- /dev/null +++ b/app/src/main/java/com/rangelreale/devsettings/tiles/KeepScreenOnTileService.kt @@ -0,0 +1,59 @@ +package com.rangelreale.devsettings.tiles + +import android.service.quicksettings.Tile +import com.rangelreale.devsettings.R +import com.rangelreale.devsettings.keepon.KeepScreenOnDuration +import com.rangelreale.devsettings.keepon.KeepScreenOnService +import com.rangelreale.devsettings.keepon.KeepScreenOnState +import com.rangelreale.devsettings.keepon.formatRemaining +import com.rangelreale.devsettings.keepon.labelRes +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch + +/** + * Each tap moves to the next duration: 5 min, 15 min, 30 min, 1 hour, indefinitely, off. + * Each step restarts the countdown from the tap. + */ +class KeepScreenOnTileService : BaseTileService() { + + override fun onListening(scope: CoroutineScope) { + scope.launch { + KeepScreenOnState.status.collectLatest { status -> + updateTile() + // Refresh the remaining time while the panel is open. + while (status?.endsAtMillis != null && isActive) { + delay(1_000) + updateTile() + } + } + } + } + + override fun onToggle() { + val next = KeepScreenOnDuration.next(KeepScreenOnState.status.value?.duration) + try { + KeepScreenOnService.apply(this, next) + } catch (e: IllegalStateException) { + // Android refused the foreground service start (ForegroundServiceStartNotAllowedException). + openApp() + } + } + + override fun render(tile: Tile) { + val status = KeepScreenOnState.status.value + if (status == null) { + renderOnOff(tile, false) + return + } + val remaining = status.remainingMillis(System.currentTimeMillis()) + val subtitle = if (remaining == null) { + getString(status.duration.labelRes) + } else { + getString(R.string.tile_time_left, formatRemaining(remaining)) + } + renderOnOff(tile, true, subtitle) + } +} diff --git a/app/src/main/java/com/rangelreale/devsettings/tiles/SettingTiles.kt b/app/src/main/java/com/rangelreale/devsettings/tiles/SettingTiles.kt new file mode 100644 index 0000000..e8a9d83 --- /dev/null +++ b/app/src/main/java/com/rangelreale/devsettings/tiles/SettingTiles.kt @@ -0,0 +1,40 @@ +package com.rangelreale.devsettings.tiles + +import android.service.quicksettings.Tile +import com.rangelreale.devsettings.R +import com.rangelreale.devsettings.data.DevSetting + +/** A tile that toggles one [DevSetting]. */ +abstract class SettingTileService(private val setting: DevSetting) : BaseTileService() { + + override val observedKeys = listOf(setting.key) + + /** Debugging tiles ask for an unlock first, so a locked phone cannot open an adb port. */ + protected open val requiresUnlock = false + + override fun onToggle() { + if (requiresUnlock && isLocked) { + unlockAndRun { + repository.toggle(setting) + updateTile() + } + } else { + repository.toggle(setting) + } + } + + override fun render(tile: Tile) = renderOnOff(tile, repository.isEnabled(setting)) +} + +class UsbDebuggingTileService : SettingTileService(DevSetting.USB_DEBUGGING) { + override val requiresUnlock = true +} + +class WirelessDebuggingTileService : SettingTileService(DevSetting.WIRELESS_DEBUGGING) { + override val requiresUnlock = true +} + +class StayAwakeTileService : SettingTileService(DevSetting.STAY_AWAKE) { + override fun render(tile: Tile) = + renderOnOff(tile, repository.isEnabled(DevSetting.STAY_AWAKE), getString(R.string.stay_awake_on_detail)) +} diff --git a/app/src/main/java/com/rangelreale/devsettings/ui/MainScreen.kt b/app/src/main/java/com/rangelreale/devsettings/ui/MainScreen.kt new file mode 100644 index 0000000..7359d92 --- /dev/null +++ b/app/src/main/java/com/rangelreale/devsettings/ui/MainScreen.kt @@ -0,0 +1,475 @@ +package com.rangelreale.devsettings.ui + +import android.Manifest +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Context +import android.content.pm.PackageManager +import android.database.ContentObserver +import android.os.Build +import android.os.Handler +import android.os.Looper +import android.provider.Settings +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.annotation.DrawableRes +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.selection.SelectionContainer +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.FilledTonalButton +import androidx.compose.material3.FilterChip +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.ListItem +import androidx.compose.material3.ListItemDefaults +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Surface +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableLongStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.LifecycleResumeEffect +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.rangelreale.devsettings.R +import com.rangelreale.devsettings.SystemScreens +import com.rangelreale.devsettings.data.DevSetting +import com.rangelreale.devsettings.data.DevSettingsRepository +import com.rangelreale.devsettings.data.GlobalKeys +import com.rangelreale.devsettings.data.WirelessDebugInfo +import com.rangelreale.devsettings.data.WriteResult +import com.rangelreale.devsettings.data.grantCommand +import com.rangelreale.devsettings.keepon.KeepScreenOnDuration +import com.rangelreale.devsettings.keepon.KeepScreenOnService +import com.rangelreale.devsettings.keepon.KeepScreenOnState +import com.rangelreale.devsettings.keepon.KeepScreenOnStatus +import com.rangelreale.devsettings.keepon.formatRemaining +import com.rangelreale.devsettings.keepon.labelRes +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch + +/** Values read from the system on each refresh. */ +private data class Snapshot( + val hasPermission: Boolean, + val developerOptions: Boolean, + val enabled: Map, +) + +private fun DevSettingsRepository.snapshot() = Snapshot( + hasPermission = hasPermission(), + developerOptions = developerOptionsEnabled(), + enabled = DevSetting.entries.associateWith { isEnabled(it) }, +) + +private val DevSetting.titleRes: Int + get() = when (this) { + DevSetting.USB_DEBUGGING -> R.string.usb_debugging + DevSetting.WIRELESS_DEBUGGING -> R.string.wireless_debugging + DevSetting.STAY_AWAKE -> R.string.stay_awake_long + } + +private val DevSetting.iconRes: Int + get() = when (this) { + DevSetting.USB_DEBUGGING -> R.drawable.ic_usb + DevSetting.WIRELESS_DEBUGGING -> R.drawable.ic_wifi + DevSetting.STAY_AWAKE -> R.drawable.ic_power + } + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun MainScreen(repository: DevSettingsRepository) { + val context = LocalContext.current + val scope = rememberCoroutineScope() + val snackbar = remember { SnackbarHostState() } + + var snapshot by remember { mutableStateOf(repository.snapshot()) } + var resumeCount by remember { mutableIntStateOf(0) } + fun refresh() { + snapshot = repository.snapshot() + } + + // Re-read on every resume: values may have changed while the app was in the background. + LifecycleResumeEffect(Unit) { + refresh() + resumeCount++ + onPauseOrDispose { } + } + + // Changes made elsewhere (system Settings, tiles, adb) appear immediately. + DisposableEffect(Unit) { + val observer = object : ContentObserver(Handler(Looper.getMainLooper())) { + override fun onChange(selfChange: Boolean) = refresh() + } + val keys = DevSetting.entries.map { it.key } + GlobalKeys.DEVELOPMENT_SETTINGS_ENABLED + keys.forEach { + context.contentResolver.registerContentObserver(Settings.Global.getUriFor(it), false, observer) + } + onDispose { context.contentResolver.unregisterContentObserver(observer) } + } + + // No callback announces a permission grant, so poll while the setup card is visible. + LaunchedEffect(snapshot.hasPermission) { + while (!snapshot.hasPermission) { + delay(2_000) + refresh() + } + } + + val keepOnStatus by KeepScreenOnState.status.collectAsStateWithLifecycle() + var pendingDisable by remember { mutableStateOf(null) } + + fun showMessage(text: String) { + scope.launch { snackbar.showSnackbar(text) } + } + + fun write(setting: DevSetting, enabled: Boolean) { + val result = repository.setEnabled(setting, enabled) + refresh() + when (result) { + WriteResult.SUCCESS -> Unit + WriteResult.MISSING_PERMISSION -> showMessage(context.getString(R.string.write_no_permission)) + WriteResult.FAILED -> + showMessage(context.getString(R.string.write_failed, context.getString(setting.titleRes))) + } + } + + fun onSwitch(setting: DevSetting, enabled: Boolean) { + val dropsConnection = setting == DevSetting.USB_DEBUGGING || setting == DevSetting.WIRELESS_DEBUGGING + if (!enabled && dropsConnection) pendingDisable = setting else write(setting, enabled) + } + + fun copy(text: String) { + val clipboard = context.getSystemService(ClipboardManager::class.java) + clipboard.setPrimaryClip(ClipData.newPlainText("adb", text)) + // Android 13 and later show their own confirmation. + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) showMessage(context.getString(R.string.copied)) + } + + Scaffold( + topBar = { TopAppBar(title = { Text(stringResource(R.string.app_name)) }) }, + snackbarHost = { SnackbarHost(snackbar) }, + ) { padding -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(padding) + .verticalScroll(rememberScrollState()) + .padding(horizontal = 16.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + if (!snapshot.hasPermission) { + SetupCard(command = grantCommand(context.packageName), onCopy = ::copy) + } + if (!snapshot.developerOptions) { + DeveloperOptionsCard(onOpenAboutPhone = { SystemScreens.openAboutPhone(context) }) + } + + Card(modifier = Modifier.fillMaxWidth()) { + SettingRow( + setting = DevSetting.USB_DEBUGGING, + checked = snapshot.enabled.getValue(DevSetting.USB_DEBUGGING), + enabled = snapshot.hasPermission, + onCheckedChange = { onSwitch(DevSetting.USB_DEBUGGING, it) }, + ) + HorizontalDivider() + SettingRow( + setting = DevSetting.WIRELESS_DEBUGGING, + checked = snapshot.enabled.getValue(DevSetting.WIRELESS_DEBUGGING), + enabled = snapshot.hasPermission, + onCheckedChange = { onSwitch(DevSetting.WIRELESS_DEBUGGING, it) }, + ) + WirelessDetails( + enabled = snapshot.enabled.getValue(DevSetting.WIRELESS_DEBUGGING), + refreshKey = resumeCount, + onCopy = ::copy, + onOpenPairing = { SystemScreens.openWirelessDebugging(context) }, + ) + HorizontalDivider() + val stayAwake = snapshot.enabled.getValue(DevSetting.STAY_AWAKE) + SettingRow( + setting = DevSetting.STAY_AWAKE, + checked = stayAwake, + enabled = snapshot.hasPermission, + onCheckedChange = { onSwitch(DevSetting.STAY_AWAKE, it) }, + stateText = if (stayAwake) stringResource(R.string.stay_awake_on_detail) else null, + ) + HorizontalDivider() + KeepScreenOnSection( + status = keepOnStatus, + enabled = snapshot.hasPermission, + onStartFailed = { showMessage(context.getString(R.string.keep_screen_on_failed)) }, + ) + } + + OutlinedButton( + onClick = { SystemScreens.openDeveloperOptions(context) }, + modifier = Modifier.fillMaxWidth(), + ) { + Text(stringResource(R.string.open_developer_options)) + } + } + } + + pendingDisable?.let { setting -> + val name = stringResource(setting.titleRes) + val link = if (setting == DevSetting.USB_DEBUGGING) "USB" else "Wi-Fi" + AlertDialog( + onDismissRequest = { pendingDisable = null }, + title = { Text(stringResource(R.string.confirm_disable_title, name)) }, + text = { Text(stringResource(R.string.confirm_disable_body, link)) }, + confirmButton = { + TextButton(onClick = { + pendingDisable = null + write(setting, false) + }) { Text(stringResource(R.string.turn_off)) } + }, + dismissButton = { + TextButton(onClick = { pendingDisable = null }) { Text(stringResource(R.string.cancel)) } + }, + ) + } +} + +@Composable +private fun SetupCard(command: String, onCopy: (String) -> Unit) { + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.errorContainer), + ) { + Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Text(stringResource(R.string.setup_title), style = MaterialTheme.typography.titleMedium) + Text(stringResource(R.string.setup_body)) + Text(stringResource(R.string.setup_step_1)) + Text(stringResource(R.string.setup_step_2)) + Surface( + color = MaterialTheme.colorScheme.surface, + shape = MaterialTheme.shapes.small, + modifier = Modifier.fillMaxWidth(), + ) { + SelectionContainer { + Text( + text = command, + fontFamily = FontFamily.Monospace, + style = MaterialTheme.typography.bodySmall, + modifier = Modifier.padding(12.dp), + ) + } + } + FilledTonalButton(onClick = { onCopy(command) }) { Text(stringResource(R.string.copy_command)) } + Text(stringResource(R.string.setup_step_3)) + } + } +} + +@Composable +private fun DeveloperOptionsCard(onOpenAboutPhone: () -> Unit) { + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.tertiaryContainer), + ) { + Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Text(stringResource(R.string.dev_options_title), style = MaterialTheme.typography.titleMedium) + Text(stringResource(R.string.dev_options_body)) + FilledTonalButton(onClick = onOpenAboutPhone) { Text(stringResource(R.string.open_about_phone)) } + } + } +} + +@Composable +private fun SettingRow( + setting: DevSetting, + checked: Boolean, + enabled: Boolean, + onCheckedChange: (Boolean) -> Unit, + stateText: String? = null, +) { + RowItem( + icon = setting.iconRes, + title = stringResource(setting.titleRes), + state = stateText ?: stringResource(if (checked) R.string.status_on else R.string.status_off), + checked = checked, + enabled = enabled, + onCheckedChange = onCheckedChange, + ) +} + +@Composable +private fun RowItem( + @DrawableRes icon: Int, + title: String, + state: String, + checked: Boolean, + enabled: Boolean, + onCheckedChange: (Boolean) -> Unit, +) { + ListItem( + colors = ListItemDefaults.colors(containerColor = Color.Transparent), + leadingContent = { Icon(painterResource(icon), contentDescription = null) }, + headlineContent = { Text(title) }, + supportingContent = { Text(state) }, + trailingContent = { Switch(checked = checked, onCheckedChange = onCheckedChange, enabled = enabled) }, + ) +} + +@Composable +private fun WirelessDetails( + enabled: Boolean, + refreshKey: Int, + onCopy: (String) -> Unit, + onOpenPairing: () -> Unit, +) { + val context = LocalContext.current + var ip by remember { mutableStateOf(null) } + var port by remember { mutableStateOf(null) } + var searching by remember { mutableStateOf(false) } + + LaunchedEffect(enabled, refreshKey) { + ip = WirelessDebugInfo.wifiIpAddress(context) + port = null + val address = ip + if (!enabled || address == null) return@LaunchedEffect + searching = true + try { + // adbd needs a moment to start listening after the setting turns on. + for (attempt in 0 until 4) { + port = WirelessDebugInfo.findPort(context, address) + if (port != null) break + delay(1_500) + } + } finally { + searching = false + } + } + + Column( + modifier = Modifier.padding(start = 56.dp, end = 16.dp, bottom = 12.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + if (enabled) { + val address = ip + val currentPort = port + when { + address == null -> Text(stringResource(R.string.wireless_no_ip), style = MaterialTheme.typography.bodySmall) + currentPort != null -> { + val endpoint = "$address:$currentPort" + Text( + stringResource(R.string.wireless_address, endpoint), + fontFamily = FontFamily.Monospace, + style = MaterialTheme.typography.bodyMedium, + ) + FilledTonalButton(onClick = { onCopy("adb connect $endpoint") }) { + Text(stringResource(R.string.copy_connect)) + } + } + else -> { + Text(stringResource(R.string.wireless_address, address), fontFamily = FontFamily.Monospace) + Text( + stringResource(if (searching) R.string.wireless_port_searching else R.string.wireless_port_unknown), + style = MaterialTheme.typography.bodySmall, + ) + } + } + } + OutlinedButton(onClick = onOpenPairing) { Text(stringResource(R.string.open_wireless_debugging)) } + } +} + +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun KeepScreenOnSection( + status: KeepScreenOnStatus?, + enabled: Boolean, + onStartFailed: () -> Unit, +) { + val context = LocalContext.current + var selected by rememberSaveable { mutableStateOf(KeepScreenOnDuration.MIN_15) } + val notificationPermission = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { } + + var now by remember { mutableLongStateOf(System.currentTimeMillis()) } + LaunchedEffect(status) { + while (status?.endsAtMillis != null) { + now = System.currentTimeMillis() + delay(1_000) + } + } + + fun start(duration: KeepScreenOnDuration) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && !context.hasNotificationPermission()) { + notificationPermission.launch(Manifest.permission.POST_NOTIFICATIONS) + } + try { + KeepScreenOnService.start(context, duration) + } catch (e: IllegalStateException) { + onStartFailed() + } + } + + val stateText = when { + status == null -> stringResource(R.string.status_off) + status.endsAtMillis == null -> stringResource(R.string.state_on_until_stopped) + else -> stringResource(R.string.state_on_time_left, formatRemaining(status.remainingMillis(now) ?: 0)) + } + + RowItem( + icon = R.drawable.ic_screen, + title = stringResource(R.string.keep_screen_on), + state = stateText, + checked = status != null, + enabled = enabled, + onCheckedChange = { on -> if (on) start(selected) else KeepScreenOnService.stop(context) }, + ) + Column(Modifier.padding(start = 56.dp, end = 16.dp, bottom = 12.dp)) { + Text(stringResource(R.string.keep_screen_on_detail), style = MaterialTheme.typography.bodySmall) + FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + KeepScreenOnDuration.entries.forEach { duration -> + val isSelected = (status?.duration ?: selected) == duration + FilterChip( + selected = isSelected, + enabled = enabled, + onClick = { + selected = duration + // While running, picking a duration restarts the countdown with it. + if (status != null) start(duration) + }, + label = { Text(stringResource(duration.labelRes)) }, + ) + } + } + } +} + +private fun Context.hasNotificationPermission(): Boolean = + Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || + checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED diff --git a/app/src/main/java/com/rangelreale/devsettings/ui/Theme.kt b/app/src/main/java/com/rangelreale/devsettings/ui/Theme.kt new file mode 100644 index 0000000..2c2cd3d --- /dev/null +++ b/app/src/main/java/com/rangelreale/devsettings/ui/Theme.kt @@ -0,0 +1,19 @@ +package com.rangelreale.devsettings.ui + +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.dynamicLightColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.ui.platform.LocalContext + +/** Light theme. Uses the wallpaper colours (dynamic color, Android 12+) when available. */ +@Composable +fun DevSettingsTheme(content: @Composable () -> Unit) { + val context = LocalContext.current + val colors = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) { + dynamicLightColorScheme(context) + } else { + lightColorScheme() + } + MaterialTheme(colorScheme = colors, content = content) +} diff --git a/app/src/main/res/drawable/ic_launcher_foreground.xml b/app/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000..37e8959 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,15 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_power.xml b/app/src/main/res/drawable/ic_power.xml new file mode 100644 index 0000000..84c1c4d --- /dev/null +++ b/app/src/main/res/drawable/ic_power.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_screen.xml b/app/src/main/res/drawable/ic_screen.xml new file mode 100644 index 0000000..cea9953 --- /dev/null +++ b/app/src/main/res/drawable/ic_screen.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_stop.xml b/app/src/main/res/drawable/ic_stop.xml new file mode 100644 index 0000000..02e24a3 --- /dev/null +++ b/app/src/main/res/drawable/ic_stop.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_usb.xml b/app/src/main/res/drawable/ic_usb.xml new file mode 100644 index 0000000..460211b --- /dev/null +++ b/app/src/main/res/drawable/ic_usb.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_wifi.xml b/app/src/main/res/drawable/ic_wifi.xml new file mode 100644 index 0000000..8160088 --- /dev/null +++ b/app/src/main/res/drawable/ic_wifi.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/mipmap-anydpi/ic_launcher.xml b/app/src/main/res/mipmap-anydpi/ic_launcher.xml new file mode 100644 index 0000000..5c84730 --- /dev/null +++ b/app/src/main/res/mipmap-anydpi/ic_launcher.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..5c3c853 --- /dev/null +++ b/app/src/main/res/values/colors.xml @@ -0,0 +1,4 @@ + + + #FF2E7D32 + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..778d990 --- /dev/null +++ b/app/src/main/res/values/strings.xml @@ -0,0 +1,59 @@ + + + Dev Settings + + USB debugging + Wireless debugging + Stay awake + Stay awake while charging + Keep screen on + + On + Off + On until stopped + On, %1$s left + On for AC, USB and wireless charging + Setup needed + %1$s left + + 5 min + 15 min + 30 min + 1 hour + Until stopped + + One-time setup + This app needs the WRITE_SECURE_SETTINGS permission. Only a computer can grant it. + 1. Turn on USB debugging in Developer options, then connect the phone to a computer. + 2. On the computer, run this command: + 3. Come back here. The switches turn on within a few seconds. + Copy command + Copied + + Developer options are off + These settings have no effect until Developer options are on. Open About phone and tap Build number seven times. On some phones, Build number is under Software information. + Open About phone + + Open Developer options + Open wireless debugging (pairing) + Address: %1$s + Looking for the debugging port… + Port not found. The wireless debugging screen shows it. + No Wi-Fi address. Wireless debugging needs Wi-Fi. + Copy adb connect + + Turn off %1$s? + A computer connected through %1$s loses its connection. + Turn off + Cancel + + Android rejected the change to %1$s. + Permission missing. Complete the setup first. + Could not start keep screen on. + + Keep screen on + Keeping the screen on + Until you stop it + Stop + Holds the screen on, charging or not. + diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..30a7a7a --- /dev/null +++ b/app/src/main/res/values/themes.xml @@ -0,0 +1,4 @@ + + +