chore: import upstream snapshot with attribution
Voice Workbench / headless workbench (mocked backends) (push) Has been cancelled
Voice Workbench / real acoustic lane (nightly, provisioned only) (push) Has been cancelled
ci / test (push) Has been cancelled
ci / lint-and-format (push) Has been cancelled
ci / build (push) Has been cancelled
ci / dev-startup (push) Has been cancelled
gitleaks / gitleaks (push) Has been cancelled
Markdown Links / Relative Markdown Links (push) Has been cancelled
Quality (Extended) / Homepage Build (PR smoke) (push) Has been cancelled
Quality (Extended) / Comment-only diff guard (push) Has been cancelled
Quality (Extended) / Format + Type Safety Ratchet (push) Has been cancelled
Quality (Extended) / Develop Gate (secret scan + UI determinism) (push) Has been cancelled
Quality (Extended) / Develop Gate (lint) (push) Has been cancelled
Chat shell gestures / Chat shell gesture + parity e2e (push) Has been cancelled
Cloud Gateway Discord / Test (push) Has been cancelled
Benchmark Bridge Tests / benchmark (bunx @biomejs/biome check packages/lifeops-bench/src, benchmark-lint) (push) Has been cancelled
Benchmark Bridge Tests / benchmark (bunx vitest run --config packages/lifeops-bench/vitest.config.ts --root packages/lifeops-bench --passWithNoTests, benchmark-tests) (push) Has been cancelled
Build Agent Image / build-and-push (push) Has been cancelled
Dev Smoke / bun run dev onboarding chat (push) Has been cancelled
Dev Smoke / Vite HMR dependency-level smoke (push) Has been cancelled
Electrobun Submodule Guard / electrobun gitlink is fetchable (push) Has been cancelled
Publish @elizaos/example-code / check_npm (push) Has been cancelled
Publish @elizaos/example-code / publish_npm (push) Has been cancelled
Publish @elizaos/plugin-elizacloud / verify_version (push) Has been cancelled
Publish @elizaos/plugin-elizacloud / publish_npm (push) Has been cancelled
Sandbox Live Smoke / Sandbox live smoke (push) Has been cancelled
Snap Build & Test / Build Snap (amd64) (push) Has been cancelled
Snap Build & Test / Build Snap (arm64) (push) Has been cancelled
Test Packaging / elizaos CLI global-install smoke (node + bun) (push) Has been cancelled
Cloud Gateway Webhook / Test (push) Has been cancelled
Cloud Tests / lint-and-types (push) Has been cancelled
Cloud Tests / unit-tests (push) Has been cancelled
Cloud Tests / integration-tests (push) Has been cancelled
Cloud Tests / e2e-tests (push) Has been cancelled
CodeQL Advanced / Analyze (javascript-typescript) (push) Has been cancelled
Deploy Apps Worker (Product 2) / Determine environment (push) Has been cancelled
Deploy Apps Worker (Product 2) / Deploy apps worker to apps-control host (${{ needs.determine-env.outputs.environment }}) (push) Has been cancelled
Deploy Eliza Provisioning Worker / Determine environment (push) Has been cancelled
Deploy Eliza Provisioning Worker / Deploy worker to Hetzner host (${{ needs.determine-env.outputs.environment }} @ ${{ needs.determine-env.outputs.deployment_sha }}) (push) Has been cancelled
Dev Smoke / Classify changed paths (push) Has been cancelled
supply-chain / sbom (push) Has been cancelled
supply-chain / vulnerability-scan (push) Has been cancelled
Build, Push & Deploy to Phala Cloud / build-and-push (push) Has been cancelled
Test Packaging / Validate Packaging Configs (push) Has been cancelled
Test Packaging / Build & Test PyPI Package (push) Has been cancelled
Test Packaging / PyPI on Python ${{ matrix.python }} (push) Has been cancelled
Test Packaging / Pack & Test JS Tarballs (push) Has been cancelled
UI Fixture E2E / ui-fixture-e2e (push) Has been cancelled
UI Fixture E2E / fixture-e2e (push) Has been cancelled
UI Story Gate / story-gate (push) Has been cancelled
vault-ci / test (macos-latest) (push) Has been cancelled
vault-ci / test (ubuntu-latest) (push) Has been cancelled
vault-ci / test (windows-latest) (push) Has been cancelled
vault-ci / app-core wiring tests (push) Has been cancelled
verify-patches / verify patches/CHECKSUMS.sha256 (push) Has been cancelled
Voice Benchmark Smoke / voice-emotion fixture smoke (push) Has been cancelled
Voice Benchmark Smoke / voiceagentbench fixture smoke (push) Has been cancelled
Voice Benchmark Smoke / voicebench-quality unit smoke (push) Has been cancelled
Voice Benchmark Smoke / voicebench TypeScript unit (no audio) (push) Has been cancelled
Voice Benchmark Smoke / voice bench smoke summary (push) Has been cancelled
Windows CI / windows ([bun run --cwd packages/app-core test bun run --cwd packages/elizaos test bun run --cwd packages/cloud/shared test], app-and-cli) (push) Has been cancelled
Windows CI / windows ([bun run --cwd packages/scenario-runner test bun run --cwd packages/vault test bun run --cwd packages/security test bun run --cwd plugins/plugin-coding-tools test], framework-packages) (push) Has been cancelled
Windows CI / windows ([bun run --cwd plugins/plugin-elizacloud test bun run --cwd plugins/plugin-discord test bun run --cwd plugins/plugin-anthropic test bun run --cwd plugins/plugin-openai test bun run --cwd plugins/plugin-app-control test bun run --cwd plugins/pl… (push) Has been cancelled
Windows CI / windows ([node packages/scripts/run-turbo.mjs run build --filter=@elizaos/core --filter=@elizaos/shared --filter=@elizaos/agent --concurrency=4 node packages/scripts/run-bash-linux-only.mjs scripts/verify-riscv64-buildpaths.sh node packages/scripts/run… (push) Has been cancelled
Windows CI / windows ([node packages/scripts/run-turbo.mjs run typecheck --filter=@elizaos/core --filter=@elizaos/shared --filter=@elizaos/cloud-shared --concurrency=4 bun run --cwd packages/core test bun run --cwd packages/shared test], core-runtime, 75) (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 12:43:05 +08:00
commit 426e9eeabd
41828 changed files with 9656266 additions and 0 deletions
@@ -0,0 +1,45 @@
ext {
junitVersion = project.hasProperty('junitVersion') ? rootProject.ext.junitVersion : '4.13.2'
androidxActivityVersion = project.hasProperty('androidxActivityVersion') ? rootProject.ext.androidxActivityVersion : '1.8.0'
}
apply plugin: 'com.android.library'
// Apply the Kotlin Android plugin so the plugin's .kt class is bundled into the
// library AAR. Without it AGP's built-in kotlinc compiles the sources but does
// NOT bundle the .class files, so the Capacitor plugin class is absent from the
// app dex at runtime (PluginLoadException -> the whole plugin set fails to load).
apply plugin: 'org.jetbrains.kotlin.android'
android {
namespace = "ai.eliza.plugins.system"
compileSdk project.hasProperty('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 34
defaultConfig {
minSdkVersion project.hasProperty('minSdkVersion') ? rootProject.ext.minSdkVersion : 23
targetSdkVersion project.hasProperty('targetSdkVersion') ? rootProject.ext.targetSdkVersion : 34
// Instrumented (androidTest) runner — exercises SystemDeviceReader's real
// device reads on a connected device/emulator (issue #9967).
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "17"
}
}
repositories {
google()
maven { url = uri(rootProject.ext.has('mavenCentralMirrorUrl') ? rootProject.ext.mavenCentralMirrorUrl : 'https://repo.maven.apache.org/maven2') }
mavenCentral()
}
dependencies {
implementation project(':capacitor-android')
implementation "androidx.activity:activity:$androidxActivityVersion"
// Instrumented test deps (issue #9967 — first androidTest for a native plugin).
androidTestImplementation "androidx.test:core:1.5.0"
androidTestImplementation "androidx.test:runner:1.5.2"
androidTestImplementation "androidx.test.ext:junit:1.1.5"
}
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application>
<!-- Test-only showcase activity for #9967 on-device screenshot/recording
evidence; renders the live SystemDeviceReader output. Exported so it
can be launched via `am start`; showWhenLocked so it captures even on
a secure-locked device. -->
<activity
android:name="ai.eliza.plugins.system.ReaderShowcaseActivity"
android:exported="true"
android:showWhenLocked="true"
android:turnScreenOn="true" />
</application>
</manifest>
@@ -0,0 +1,63 @@
package ai.eliza.plugins.system
import android.app.Activity
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.Gravity
import android.widget.ScrollView
import android.widget.TextView
/**
* Test-only Activity that renders the live [SystemDeviceReader] output on-screen
* so the on-device instrumented coverage can be captured as a real screenshot /
* screen recording (issue #9967 evidence). It is `setShowWhenLocked` so it can
* be captured even on a secure-locked device, and declared exported in the
* androidTest manifest so it can be launched via `am start`.
*/
class ReaderShowcaseActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
setShowWhenLocked(true)
setTurnScreenOn(true)
}
val reader = SystemDeviceReader(this)
val status = reader.readStatus()
val settings = reader.readDeviceSettings()
val text = buildString {
appendLine("SystemDeviceReader — live on-device reads (#9967)")
appendLine("package: ${status.packageName}")
appendLine()
appendLine("ROLES (live RoleManager):")
for (r in status.roles) {
appendLine(" ${r.role}: available=${r.available} held=${r.held}")
}
appendLine()
appendLine("DEVICE SETTINGS (live):")
appendLine(
" brightness=%.2f mode=%s canWrite=%s".format(
settings.brightness,
settings.brightnessMode,
settings.canWriteSettings,
),
)
appendLine(" volumes:")
for (v in settings.volumes) {
appendLine(" ${v.stream}: ${v.current}/${v.max}")
}
}
val textView = TextView(this).apply {
this.text = text
setTextColor(Color.WHITE)
setBackgroundColor(Color.parseColor("#0B132B"))
textSize = 15f
gravity = Gravity.TOP
setPadding(56, 120, 56, 56)
}
setContentView(ScrollView(this).apply { addView(textView) })
}
}
@@ -0,0 +1,107 @@
package ai.eliza.plugins.system
import android.content.Context
import android.media.AudioManager
import android.os.Build
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
/**
* The first on-device instrumented test for an elizaOS native plugin (issue
* #9967: "Kotlin runs on no test, on no device").
*
* Runs on a real device/emulator and exercises the ACTUAL Android system reads
* that the launcher's System/Settings view depends on — `RoleManager`,
* `AudioManager`, and `Settings` via [SystemDeviceReader] — asserting real
* native side-effects (state reads), not a mocked `Capacitor.Plugins` bridge.
*
* Run: `./gradlew :elizaos-capacitor-system:connectedDebugAndroidTest`
* (from packages/app-core/platforms/android, with a device/emulator attached).
*/
@RunWith(AndroidJUnit4::class)
class SystemDeviceReaderInstrumentedTest {
private val context: Context
get() = InstrumentationRegistry.getInstrumentation().targetContext
@Test
fun readStatus_returnsRealPackageNameAndRoles() {
val status = SystemDeviceReader(context).readStatus()
// packageName is the real instrumented target package, not a stub.
assertEquals(context.packageName, status.packageName)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// Every declared launcher role is reported, in order, from the live
// RoleManager — not the 0-length array the web stub / mock returns.
assertEquals(
listOf("home", "dialer", "sms", "assistant"),
status.roles.map { it.role },
)
for (role in status.roles) {
assertEquals(
"androidRole must match the RoleManager constant",
SystemDeviceReader.ROLE_MAP[role.role],
role.androidRole,
)
// `held` is consistent with the live holders list (the real
// device side-effect: who actually owns the role right now).
assertEquals(
role.holders.contains(context.packageName),
role.held,
)
}
} else {
assertTrue("roles are empty below Android 10", status.roles.isEmpty())
}
}
@Test
fun readDeviceSettings_returnsRealBrightnessAndEveryVolumeStream() {
val reader = SystemDeviceReader(context)
val settings = reader.readDeviceSettings()
// Brightness read off the live device, normalized to [0, 1].
assertTrue(
"brightness ${settings.brightness} must be in [0,1]",
settings.brightness in 0.0..1.0,
)
assertTrue(
"brightnessMode must be a known mode",
settings.brightnessMode in setOf("manual", "automatic", "unknown"),
)
// Every audio stream is reported with real AudioManager bounds.
assertEquals(
SystemDeviceReader.VOLUME_STREAM_MAP.keys.toList(),
settings.volumes.map { it.stream },
)
val audio = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
for (volume in settings.volumes) {
val stream = SystemDeviceReader.VOLUME_STREAM_MAP.getValue(volume.stream)
assertTrue(
"${volume.stream} max ${volume.max} must be positive",
volume.max > 0,
)
assertTrue(
"${volume.stream} current ${volume.current} must be within [0, max]",
volume.current in 0..volume.max,
)
// The reader's bounds match a direct, independent AudioManager read.
assertEquals(audio.getStreamMaxVolume(stream), volume.max)
}
}
@Test
fun canWriteSettings_returnsLiveGrantState() {
// Just asserts the real permission probe runs on-device without
// throwing and returns a concrete boolean (Settings.System.canWrite).
val value = SystemDeviceReader(context).canWriteSettings()
assertNotNull(value)
}
}
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
</manifest>
@@ -0,0 +1,171 @@
package ai.eliza.plugins.system
import android.app.role.RoleManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.media.AudioManager
import android.os.Build
import android.provider.Settings
import android.provider.Telephony
import android.telecom.TelecomManager
/**
* Pure, [Context]-backed reader for the Android system state that [SystemPlugin]
* exposes to the launcher's System/Settings views (role status + device
* settings).
*
* The read logic used to live inside the Capacitor [com.getcapacitor.Plugin],
* coupled to a `PluginCall`/`Bridge`, which is exactly why it "ran on no test,
* on no device" (issue #9967): you could not exercise the real Android reads
* without standing up a WebView bridge. Extracting it here lets an instrumented
* `androidTest` drive the actual device APIs (`RoleManager`, `AudioManager`,
* `Settings`) against a real phone/emulator. [SystemPlugin] delegates to this
* reader and builds its JS response from these values unchanged, so the wire
* contract is identical.
*/
class SystemDeviceReader(private val context: Context) {
data class RoleStatus(
val role: String,
val androidRole: String,
val available: Boolean,
val held: Boolean,
val holders: List<String>,
)
data class SystemStatus(
val packageName: String,
val roles: List<RoleStatus>,
)
data class VolumeStatus(
val stream: String,
val current: Int,
val max: Int,
)
data class DeviceSettings(
val brightness: Double,
val brightnessMode: String,
val canWriteSettings: Boolean,
val volumes: List<VolumeStatus>,
)
/** Package name + per-role status (home/dialer/sms/assistant). Roles are
* empty below Android 10 (RoleManager unavailable), matching the original. */
fun readStatus(): SystemStatus {
val roles = mutableListOf<RoleStatus>()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val roleManager = context.getSystemService(Context.ROLE_SERVICE) as RoleManager
for ((name, androidRole) in ROLE_MAP) {
val available = roleManager.isRoleAvailable(androidRole)
val holders = if (available) roleHolders(name) else emptyList()
roles.add(
RoleStatus(
role = name,
androidRole = androidRole,
available = available,
held = holders.contains(context.packageName),
holders = holders,
),
)
}
}
return SystemStatus(packageName = context.packageName, roles = roles)
}
/** Brightness (01), brightness mode, WRITE_SETTINGS grant, and volume
* levels for every audio stream — all read from the live device. */
fun readDeviceSettings(): DeviceSettings {
val audio = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
return DeviceSettings(
brightness = readBrightness(),
brightnessMode = readBrightnessMode(),
canWriteSettings = canWriteSettings(),
volumes = VOLUME_STREAM_MAP.map { (name, stream) -> readVolume(name, stream, audio) },
)
}
/** Single-stream volume status (used by the write path's response). */
fun readVolume(name: String, stream: Int, audio: AudioManager): VolumeStatus =
VolumeStatus(
stream = name,
current = audio.getStreamVolume(stream),
max = audio.getStreamMaxVolume(stream),
)
fun canWriteSettings(): Boolean =
Build.VERSION.SDK_INT < Build.VERSION_CODES.M || Settings.System.canWrite(context)
private fun roleHolders(name: String): List<String> = when (name) {
"home" -> listOfNotNull(resolveHomePackage())
"dialer" -> listOfNotNull(resolveDefaultDialerPackage())
"sms" -> listOfNotNull(Telephony.Sms.getDefaultSmsPackage(context))
"assistant" -> listOfNotNull(resolveAssistantPackage())
else -> emptyList()
}
private fun resolveHomePackage(): String? {
val intent = Intent(Intent.ACTION_MAIN)
intent.addCategory(Intent.CATEGORY_HOME)
return context.packageManager.resolveActivity(intent, 0)?.activityInfo?.packageName
}
private fun resolveDefaultDialerPackage(): String? {
val telecom = context.getSystemService(Context.TELECOM_SERVICE) as? TelecomManager
return telecom?.defaultDialerPackage
}
private fun resolveAssistantPackage(): String? {
val flattened = Settings.Secure.getString(context.contentResolver, "assistant")
if (flattened.isNullOrBlank()) return null
return ComponentName.unflattenFromString(flattened)?.packageName
}
private fun readBrightness(): Double {
return try {
Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS)
.coerceIn(0, 255) / 255.0
} catch (_: Settings.SettingNotFoundException) {
0.75
}
}
private fun readBrightnessMode(): String {
return try {
when (
Settings.System.getInt(
context.contentResolver,
Settings.System.SCREEN_BRIGHTNESS_MODE,
)
) {
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL -> "manual"
Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC -> "automatic"
else -> "unknown"
}
} catch (_: Settings.SettingNotFoundException) {
"unknown"
}
}
companion object {
/** role name → Android RoleManager constant, in launcher display order. */
val ROLE_MAP: Map<String, String> = linkedMapOf(
"home" to RoleManager.ROLE_HOME,
"dialer" to RoleManager.ROLE_DIALER,
"sms" to RoleManager.ROLE_SMS,
"assistant" to RoleManager.ROLE_ASSISTANT,
)
/** volume stream name → AudioManager stream constant. */
val VOLUME_STREAM_MAP: Map<String, Int> = linkedMapOf(
"music" to AudioManager.STREAM_MUSIC,
"ring" to AudioManager.STREAM_RING,
"alarm" to AudioManager.STREAM_ALARM,
"notification" to AudioManager.STREAM_NOTIFICATION,
"system" to AudioManager.STREAM_SYSTEM,
"voiceCall" to AudioManager.STREAM_VOICE_CALL,
)
}
}
@@ -0,0 +1,231 @@
package ai.eliza.plugins.system
import android.app.role.RoleManager
import android.content.Context
import android.content.Intent
import android.media.AudioManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.activity.result.ActivityResult
import com.getcapacitor.JSArray
import com.getcapacitor.JSObject
import com.getcapacitor.Plugin
import com.getcapacitor.PluginCall
import com.getcapacitor.PluginMethod
import com.getcapacitor.annotation.ActivityCallback
import com.getcapacitor.annotation.CapacitorPlugin
@CapacitorPlugin(name = "ElizaSystem")
class SystemPlugin : Plugin() {
// Device reads are delegated to a pure, Context-backed reader so they can be
// exercised by an instrumented androidTest without a Capacitor Bridge / WebView
// (issue #9967). This plugin stays a thin Capacitor binding: read via the
// reader, then marshal the result into the unchanged JS wire shape.
private val reader by lazy { SystemDeviceReader(context) }
@PluginMethod
fun getStatus(call: PluginCall) {
call.resolve(statusToJs(reader.readStatus()))
}
@PluginMethod
fun requestRole(call: PluginCall) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
call.reject("Android role requests require Android 10 or newer")
return
}
val roleName = call.getString("role")?.trim()
val androidRole = SystemDeviceReader.ROLE_MAP[roleName]
if (roleName.isNullOrEmpty() || androidRole == null) {
call.reject("role must be one of ${SystemDeviceReader.ROLE_MAP.keys.joinToString(", ")}")
return
}
val roleManager = context.getSystemService(Context.ROLE_SERVICE) as RoleManager
if (!roleManager.isRoleAvailable(androidRole)) {
call.reject("$androidRole is not available on this device")
return
}
if (roleManager.isRoleHeld(androidRole)) {
call.resolve(roleRequestResult(roleName, true, 0))
return
}
startActivityForResult(
call,
roleManager.createRequestRoleIntent(androidRole),
"handleRoleRequestResult"
)
}
@ActivityCallback
private fun handleRoleRequestResult(call: PluginCall, result: ActivityResult) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
call.reject("Android role requests require Android 10 or newer")
return
}
val roleName = call.getString("role")?.trim()
val androidRole = SystemDeviceReader.ROLE_MAP[roleName]
if (roleName.isNullOrEmpty() || androidRole == null) {
call.reject("role must be one of ${SystemDeviceReader.ROLE_MAP.keys.joinToString(", ")}")
return
}
val roleManager = context.getSystemService(Context.ROLE_SERVICE) as RoleManager
call.resolve(roleRequestResult(roleName, roleManager.isRoleHeld(androidRole), result.resultCode))
}
private fun roleRequestResult(roleName: String, held: Boolean, resultCode: Int): JSObject {
val result = JSObject()
result.put("role", roleName)
result.put("held", held)
result.put("resultCode", resultCode)
return result
}
@PluginMethod
fun openSettings(call: PluginCall) {
val intent = Intent(Settings.ACTION_SETTINGS)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
call.resolve()
}
@PluginMethod
fun openNetworkSettings(call: PluginCall) {
val intent = Intent(Settings.ACTION_WIFI_SETTINGS)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
call.resolve()
}
@PluginMethod
fun openWriteSettings(call: PluginCall) {
val intent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS, Uri.parse("package:${context.packageName}"))
} else {
Intent(Settings.ACTION_SETTINGS)
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
call.resolve()
}
@PluginMethod
fun openDisplaySettings(call: PluginCall) {
val intent = Intent(Settings.ACTION_DISPLAY_SETTINGS)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
call.resolve()
}
@PluginMethod
fun openSoundSettings(call: PluginCall) {
val intent = Intent(Settings.ACTION_SOUND_SETTINGS)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
call.resolve()
}
@PluginMethod
fun getDeviceSettings(call: PluginCall) {
call.resolve(deviceSettingsToJs(reader.readDeviceSettings()))
}
@PluginMethod
fun setScreenBrightness(call: PluginCall) {
val brightness = call.getDouble("brightness")
if (brightness == null || brightness.isNaN()) {
call.reject("brightness must be a number between 0 and 1")
return
}
val clamped = brightness.coerceIn(0.0, 1.0)
if (!reader.canWriteSettings()) {
call.reject("WRITE_SETTINGS permission is required to change system brightness")
return
}
try {
Settings.System.putInt(
context.contentResolver,
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL
)
Settings.System.putInt(
context.contentResolver,
Settings.System.SCREEN_BRIGHTNESS,
(clamped * 255.0).toInt().coerceIn(0, 255)
)
call.resolve(deviceSettingsToJs(reader.readDeviceSettings()))
} catch (error: RuntimeException) {
call.reject("Failed to set screen brightness", error)
}
}
@PluginMethod
fun setVolume(call: PluginCall) {
val streamName = call.getString("stream")?.trim()
val stream = SystemDeviceReader.VOLUME_STREAM_MAP[streamName]
if (streamName.isNullOrEmpty() || stream == null) {
call.reject("stream must be one of ${SystemDeviceReader.VOLUME_STREAM_MAP.keys.joinToString(", ")}")
return
}
val volume = call.getInt("volume")
if (volume == null) {
call.reject("volume is required")
return
}
val showUi = call.getBoolean("showUi") ?: false
val audio = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
val max = audio.getStreamMaxVolume(stream)
val clamped = volume.coerceIn(0, max)
val flags = if (showUi) AudioManager.FLAG_SHOW_UI else 0
try {
audio.setStreamVolume(stream, clamped, flags)
call.resolve(volumeToJs(reader.readVolume(streamName, stream, audio)))
} catch (error: RuntimeException) {
call.reject("Failed to set $streamName volume", error)
}
}
private fun statusToJs(status: SystemDeviceReader.SystemStatus): JSObject {
val result = JSObject()
result.put("packageName", status.packageName)
val roles = JSArray()
for (role in status.roles) {
val item = JSObject()
item.put("role", role.role)
item.put("androidRole", role.androidRole)
item.put("available", role.available)
item.put("held", role.held)
item.put("holders", JSArray(role.holders))
roles.put(item)
}
result.put("roles", roles)
return result
}
private fun deviceSettingsToJs(settings: SystemDeviceReader.DeviceSettings): JSObject {
val result = JSObject()
result.put("brightness", settings.brightness)
result.put("brightnessMode", settings.brightnessMode)
result.put("canWriteSettings", settings.canWriteSettings)
val volumes = JSArray()
for (volume in settings.volumes) {
volumes.put(volumeToJs(volume))
}
result.put("volumes", volumes)
return result
}
private fun volumeToJs(volume: SystemDeviceReader.VolumeStatus): JSObject {
val result = JSObject()
result.put("stream", volume.stream)
result.put("current", volume.current)
result.put("max", volume.max)
return result
}
}