Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

Repository files navigation

Device Resource Tracker

A low-overhead Android app (Kotlin + Jetpack Compose) that monitors, visualizes, and logs hardware resource usage in real time. Built to benchmark device performance during Portkey (phone-to-phone screen mirroring) test sessions across multiple physical devices, so results are directly comparable device-to-device.

What it does

  • Runs a foreground service that samples CPU, memory, battery/power, thermal status, and Wi-Fi link quality on a configurable cadence (1s / 5s / 10s), independent of whatever app is on screen — including during a live Portkey session where this app itself isn't visible.
  • Shows a live Compose dashboard (gauges + trend lines) for each metric, laid out in a responsive grid so the same screen reads consistently on a low-end phone or a tablet.
  • Streams every sample straight to a timestamped CSV file in the app's private external files directory as it's collected, and can additionally export the session as JSON on demand.
  • Stamps every export with device-identifying metadata (model, build fingerprint, best-effort serial/ID, Android version, GMS Core version) so files pulled off several phones are still unambiguous once they're off the device.

Architecture

collectors/   — one class per metric source (CPU, memory, battery, thermal, Wi-Fi, foreground app)
model/        — plain data classes shared across layers (MetricSnapshot, DeviceMetadata, ...)
data/         — MetricsRepository (shared state), CsvSessionWriter, JsonSessionExporter
service/      — MetricsForegroundService (owns the polling loop) + notification helper
ui/           — Compose dashboard, reusable metric-card/gauge/chart components, theme
widget/       — Glance home screen widget (state keys, updater, UI, toggle action, receiver)
  • MetricsForegroundService is the only producer. It samples every collector on the current polling interval (off the main thread, via coroutines/Dispatchers.IO), pushes each MetricSnapshot into MetricsRepository, and updates the persistent notification.
  • MetricsRepository is a plain singleton (not a DI graph) — the entire app has one long-lived data stream, and adding Hilt/Room/etc. would only add startup cost to a tool whose whole point is not skewing the numbers it measures. It exposes StateFlows the Compose UI collects with collectAsStateWithLifecycle, and owns the streaming CSV writer.
  • CPU sampling reads /proc/stat and diffs successive reads (standard jiffy-counter approach) rather than sleeping mid-tick, so there's no extra busy-wait — the existing poll interval doubles as the diff window. Verified on real hardware (a userdebug/dev-keys Pixel device) that some builds deny /proc/stat to third-party apps outright — no denial is even logged (a silent sepolicy dontaudit rule), so this can't be treated as a hypothetical edge case. When that happens, CpuUsageCollector permanently switches (for the rest of the process's life — no point retrying a syscall known to fail) to a coarser fallback: the ratio of each core's current to max scaling frequency, read from /sys/devices/system/cpu/cpuN/cpufreq/*, averaged across cores. Every MetricSnapshot and export row carries a cpuUsageSource (proc_stat or freq_ratio) so the two methods are never silently conflated when comparing sessions across devices.
  • Thermal status is event-driven (PowerManager.addThermalStatusListener) rather than polled, so a throttling transition is caught immediately, not just at the next tick.
  • Charts/gauges are hand-rolled with Compose Canvas — no charting dependency, keeping the app's own footprint smaller.

Manifest permissions

Permission Why it's needed
FOREGROUND_SERVICE Lets the tracker run as a foreground service so sampling continues no matter what app is on screen.
FOREGROUND_SERVICE_SPECIAL_USE Android 14+ requires every foreground service to declare a type. Continuous hardware-metric sampling doesn't fit any standard category (location, media, dataSync, etc.), so it uses the "special use" type added for exactly this case (see the PROPERTY_SPECIAL_USE_FGS_SUBTYPE description in the manifest).
POST_NOTIFICATIONS Required on Android 13+ to actually display the persistent tracking notification. The foreground service still runs without it — it just won't be visible — so this is requested at startup.
ACCESS_WIFI_STATE Reads current Wi-Fi connection info (RSSI, link speed, connection state, frequency) for the network panel. Band and 802.11 channel are derived from the frequency locally (WifiBandInfo) — no extra permission needed for those.
ACCESS_FINE_LOCATION / ACCESS_COARSE_LOCATION Since Android 8.1, WifiInfo only returns real RSSI/link-speed values to apps holding a location permission (this data can be used to infer physical location, so the platform gates it). Requested as a runtime permission from the dashboard; if declined, RSSI/link speed just show as unavailable. Both FINE and COARSE are declared because Android 12+ requires it whenever FINE is requested.
PACKAGE_USAGE_STATS (optional) Only needed for the foreground-app-tracking panel. This is a special access permission — it cannot be granted through a runtime dialog. Each test device must enable it manually, once, via: Settings → Apps → Special app access → Usage access → Device Resource Tracker → Allow. If you don't need to correlate resource spikes with the on-screen app, delete this manifest line, the ForegroundAppCollector, and the toggle in ControlsBar/DashboardScreen to keep the permission surface minimal.

Not requested, and intentionally out of scope:

  • READ_PHONE_STATE — Build.getSerial() needs it pre-API 29, and from API 29 onward returns Build.UNKNOWN to normal apps regardless of permissions anyway. DeviceMetadata attempts it and falls back to Settings.Secure.ANDROID_ID (still unique per device+app, which is all the export header needs).
  • IPowerStats / any HAL access — internal AIDL interfaces, not reachable from a normal app even with FOREGROUND_SERVICE. Power draw is read entirely through the public BatteryManager API.
  • dumpsys dropbox / crash log access — requires system-level privileges this app doesn't have. Crash/dropbox correlation stays in the existing adb shell dumpsys dropbox --print workflow, run externally.

Handling unsupported/unreliable readings

Every collector is defensive rather than assuming success:

  • /proc/stat read failures → falls back to the CPU-frequency-ratio proxy described above (cpuUsageSource = "freq_ratio") rather than reporting "N/A" for the rest of the session. Only reports null/"N/A" if neither method is available.
  • BatteryManager.getIntProperty(BATTERY_PROPERTY_CURRENT_NOW) returning Integer.MIN_VALUE (unsupported on that hardware) → surfaced as null / "Unsupported", never as a bogus number.
  • Thermal APIs are API 29+; older devices simply report "Unsupported" for that panel.
  • Wi-Fi RSSI without location permission, or while disconnected, reads as unavailable instead of a stale/dummy value.
  • PACKAGE_USAGE_STATS not yet granted → the foreground-app panel says so explicitly, with a button that opens the Usage Access settings screen directly.

Using it

  1. Install and launch the app; grant the notification and location permission prompts (both are optional — the app degrades gracefully either way).

  2. Pick a polling interval (1s / 5s / 10s) and export format (CSV streams continuously either way; JSON is exported on demand).

  3. Tap Start tracking — this starts the foreground service, which keeps sampling even after you switch to Portkey or any other app.

  4. Run your Portkey session.

  5. Tap Stop tracking when done. Optionally tap Export to grab a JSON snapshot of the whole session; the CSV log was already written incrementally throughout. A confirmation banner names the exact file that was written and stays up long enough to act on — its Share action hands that file straight to another app (Drive, email, etc.) via a scoped FileProvider URI, which also doubles as an easy way to confirm the export actually happened.

  6. Pull the data off the device:

    adb pull /sdcard/Android/data/com.personal.deviceresource/files/sessions

    Every file — CSV or JSON — starts with device metadata (model, manufacturer, build fingerprint, Android version, best-effort serial/Android ID, GMS Core version) so exports from multiple devices stay unambiguous once they're off the phones. Wi-Fi rows include the raw frequency (wifi_frequency_mhz) plus the derived wifi_band (2.4/5/6 GHz) and wifi_channel, so signal drops can be correlated with the specific channel/band in use.

Home screen widget

A 2×2 Glance widget ("Device Resource") mirrors the live dashboard on the home screen so you can glance at resource usage without opening the app. It shows CPU, RAM, battery, thermal, and Wi-Fi in a compact grid, plus a Start/Stop button that controls the foreground service directly — no need to open the app at all.

Adding the widget

  1. Long-press an empty area of the home screen → Widgets.
  2. Search for "Device Resource" or scroll to find it.
  3. Drag the widget onto the home screen. It supports resizing (both axes), with a default 2×2 footprint.

How it works

  • The widget is built with Jetpack Glance 1.2.0-rc01 (the RC was chosen over 1.1.1 stable because Dp-based modifier overloads — padding, size, background(Color), cornerRadius, etc. — were only added in 1.2.0; 1.1.1 only exposes @DimenRes Int variants which would make the layout code impractical).
  • Widget state is stored via PreferencesGlanceStateDefinition (Glance's built-in SharedPreferences-backed state). The foreground service pushes updates to this state through WidgetUpdater, which is throttled to a minimum 2-second interval so the widget never updates faster than the polling cadence.
  • MetricsForegroundService calls WidgetUpdater.pushTrackingState() on start/stop and WidgetUpdater.pushSnapshot() on each polling tick, so the widget reflects the live data stream without the widget itself doing any polling.
  • The Start/Stop button is a Glance ActionCallback (ToggleTrackingAction) that optimistically flips the tracking state in widget preferences, recomposes the widget, then starts or stops MetricsForegroundService via ContextCompat.startForegroundService() / startService().
  • updatePeriodMillis is set to 0 in the widget info XML — the service is the sole driver of updates, which avoids redundant system-triggered recompositions.
  • Before the first sample arrives, the widget shows a "Waiting for first sample…" placeholder.

Widget files

widget/  — WidgetKeys (Preferences keys), WidgetUpdater (push from service),
           MetricsWidget (GlanceAppWidget + Compose UI), ToggleTrackingAction
           (Start/Stop ActionCallback), MetricsWidgetReceiver
res/xml/metrics_widget_info.xml  — appwidget-provider metadata
res/layout/widget_loading.xml    — pre-composition loading layout

Known simplifications

  • WifiManager.connectionInfo is deprecated in favor of ConnectivityManager.NetworkCallback + TransportInfo, but remains functional; used here for simplicity in a single-purpose internal tool rather than the newer callback-based API.
  • Wi-Fi band/channel are computed manually from frequency (WifiBandInfo) with the standard 802.11 formulas, rather than via ScanResult.convertFrequencyMhzToChannelIfSupported (API 30+), so the result is identical across every supported API level instead of depending on which devices happen to have the newer helper.
  • The in-memory chart history is a bounded ring buffer (last ~120 samples) so UI memory use doesn't grow with session length; the full session is instead streamed straight to the CSV file on disk, and buffered in memory only for on-demand JSON export (negligible at 1-10s polling rates even over multi-hour sessions).

Security hardening

This app is a personal benchmarking tool, not a Play Store product. Two hardening measures are built in for running it on a real phone:

Non-debuggable release build

The release build type is signed with the standard Android debug keystore (the same key AGP uses for debug builds), so a non-debuggable APK can be built and installed with a single command:

./gradlew assembleRelease
adb install -r app/build/outputs/apk/release/app-release.apk

The release APK is functionally identical to the debug build (same permissions, same service, same widget, same collectors) but with debuggable=false, which eliminates the adb run-as and debugger-attach surface that debug builds expose. Since it's signed with the same key, it can update over an already-installed debug build without requiring an uninstall first.

Backup disabled

android:allowBackup="false" is set in the manifest. This prevents app data (including the widget's last-known metric state) from being extracted via adb backup or included in Google's auto-backup/restore. For a benchmarking tool, there's no need to restore old metric history to a new device, and disabling backup closes a data-extraction path on devices with USB debugging enabled.

What's intentionally not hardened

  • Export files are plaintext — CSV/JSON files in getExternalFilesDir/sessions/ are unencrypted by design. The whole point is pulling readable data off the device to compare across phones. Encrypting would add friction without real benefit for a single-user tool.
  • No network communication — The app declares no INTERNET permission and makes zero network calls. There is no data exfiltration surface from the app itself.
  • FileProvider is scoped — Only the sessions/ subdirectory is exposed for sharing via FileProvider. No other app data is reachable through it.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages