Replace ImageReader capture with MediaCodec encode/decode for Amlogic.
Android CI / build (push) Canceled after 0s

Fixes black frames on Ugoos X5M Pro, stabilizes Home/resume, settings framerate crash, and ships a debug APK under dist/apk.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
robinandCursor committed 2026-07-19 14:52:46 +02:00
1 parent b9cbbfa13d
commit 063a068620
17 files changed
+900 -411

No files matched your search

+9
View File
@@ -5,6 +5,15 @@
# [v3.0.1-mediacodec]
### Changes
- Capture pipeline: ImageReader → MediaCodec encoder Surface → decode → RGB (Amlogic black-frame fix)
- VirtualDisplay uses AUTO_MIRROR; Android 14+ default-display MediaProjectionConfig
- Debug logging for permission, codec, non-zero pixels, send FPS
- See PIPELINE_CHANGELOG.md
---
# [v3.0] # [v3.0]
### Changes ### Changes
- Frame processing pipeline optimization with ring buffer zero-copy - Frame processing pipeline optimization with ring buffer zero-copy
+36
View File
@@ -0,0 +1,36 @@
# Pipeline-Changelog – MediaCodec Capture
## Branch: `feature/mediacodec-capture-pipeline` (v3.0.1-mediacodec)
### Problem
Auf Ugoos X5M Pro (Amlogic S905X5M, Android 14):
- FlatBuffers-Verbindung zu Hyperion OK
- MediaProjection-Permission OK
- Playstore-Screenrecorder / scrcpy: **Bild OK**
- Hyperion Grabber (ImageReader): **schwarze Frames**
### Ursache
`MediaProjection → VirtualDisplay → ImageReader` liefert auf diesem SoC keine nutzbaren Pixel.
Encoder-Surfaces (MediaCodec / MediaRecorder) schon — wie bei scrcpy und Screenrecordern.
### Änderung
| Komponente | Vorher | Nachher |
|------------|--------|---------|
| Capture-Consumer | `ImageReader` (RGBA) | `MediaCodec` Encoder-Input-Surface |
| Pixelgewinnung | `acquireLatestImage()` | Encode H.264 → Decode → `getOutputImage()` YUV→RGB |
| VirtualDisplay-Flags | `VIRTUAL_DISPLAY_FLAG_PUBLIC` | `VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR` |
| Consent (API 34+) | Standard-Intent | `MediaProjectionConfig.createConfigForDefaultDisplay()` |
| Capture-Auflösung | LED-Größe (≤128×72) direkt | Codec-freundlich (~640px Breite), dann Downscale |
| Logging | meist aus | Permission, VD, Codec, Non-Zero, Send-FPS |
### Betroffene Dateien
- `common/.../HyperionScreenEncoder.java` — Pipeline-Umbau
- `common/.../util/MediaProjectionHelper.java` — neu
- `BootActivity`, `ToggleActivity`, Mobile/TV `MainActivity` — Capture-Intent
- `HyperionScreenService.java` — Debug-Logs
- `README.md`, dieses Changelog
### Stabilität (X5M Freeze)
- Problem: Codec-Pump alle 1 ms + Capture 960×540 @ 4 Mbit → Gerät eingefroren, App/Settings nicht nutzbar
- Fix: Capture zurück auf **640×360**, Bitrate ~1.5 Mbit, Pump an Ziel-FPS, Letterbox-Crop sofort locken
- Preferences: null-sicheres Caching + robustes `getInt` (leere Strings)
+64 -13
View File
@@ -1,25 +1,76 @@
<img width="1280" height="640" alt="Hyperion Grabber Reborn" src="https://github.com/user-attachments/assets/80f2cdb0-f79a-47b9-ac09-efedaf90931a" /> <img width="1280" height="640" alt="Hyperion Grabber Reborn" src="https://github.com/user-attachments/assets/80f2cdb0-f79a-47b9-ac09-efedaf90931a" />
# Hyperion Android Reborn # Hyperion Android Reborn
Screen grabber for hyperion, updated for **Android 12** and **beyond**. Screen grabber for Hyperion / HyperHDR, updated for **Android 12–14** (inkl. Android TV).
This application will send the content of the android screen to a hyperion instance to handle the image. Die App sendet den Android-Bildschirminhalt per FlatBuffers an eine Hyperion-Instanz.
Info about hyperion can be found on their website:
https://hyperion-project.org/
Info zu Hyperion: https://hyperion-project.org/
--- ---
# Important information for TCL tvs. ## Capture-Pipeline (ab 3.0.1)
For TCL televisions, the TCL watchdog will cause the app to close in the background, please run these steps to stop this from happening.
Go to Settings > Apps > Hyperion Grabber **ALT (auf manchen Amlogic-Geräten schwarz):**
Enable "Auto-start" or "Allow background activity" permission `MediaProjection → VirtualDisplay → ImageReader → RGB → FlatBuffers`
Some TCL TVs have this in Settings > Privacy > Special app access > Auto-start
**NEU (scrcpy-/Recorder-ähnlich):**
`MediaProjection → VirtualDisplay → MediaCodec-Encoder-Surface → H.264 → MediaCodec-Decoder → YUV→RGB → Downscale → FlatBuffers`
Grund: Auf Geräten wie der **Ugoos X5M Pro (S905X5M, Android 14)** liefert ImageReader als VirtualDisplay-Consumer dauerhaft schwarze Frames, während Encoder-Surfaces (Screenrecorder, scrcpy) korrektes Bild liefern.
Weitere Änderungen:
- `VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR` statt nur `PUBLIC`
- Android 14+: `MediaProjectionConfig.createConfigForDefaultDisplay()` für Vollbild-Capture
- Debug-Logging: Permission, VirtualDisplay, Codec-Format, Frame-Größe, Non-Zero-Pixel-Check, Send-FPS
--- ---
# Download ## Build & Install (ADB Wireless)
Both **TV** and **Mobile** apps are within [releases page](https://github.com/haumlab/hyperion-android-reborn/releases)
Voraussetzungen: Android SDK / Android Studio, Gerät im selben Netz mit Wireless Debugging.
```bash
# ADB verbinden (Beispiel X5M Pro)
adb connect 10.0.10.72:5555
adb devices
# Debug-Build bauen & installieren
./gradlew installDebug
# Windows:
gradlew.bat installDebug
# Logcat (Capture-Pipeline)
adb logcat -s HyperionScreenEncoder:I HyperionScreenService:I MediaProjectionHelper:I
```
Hyperion-Server in der App konfigurieren (Beispiel): Host `10.0.50.2`, Port `19400`.
### Settings
| Einstellung | Bedeutung |
|-------------|-----------|
| Host / Port | Hyperion FlatBuffers (Default-Port 19400) |
| Priority | Hyperion-Quellenpriorität |
| Framerate | Ziel-FPS der gesendeten Frames |
| LED X / Y | Basis für Output-Auflösung (Downscale) |
| Average color | Optional nur Mittelwertfarbe senden |
---
## Bekannte Limitierungen
- DRM-geschützte Inhalte (Netflix o.ä.) bleiben schwarz — erwartet, kein Bypass.
- Encode→Decode kostet etwas CPU/Latenz gegenüber ImageReader; für LED-Ambilight (~niedrige Auflösung) i.d.R. unkritisch.
- Hardware-Encoder brauchen Mindestauflösung (hier Capture bis ca. 640px Breite, dann Downscale auf LED-Größe).
---
## Wichtig für TCL-TVs
Settings → Apps → Hyperion Grabber → Auto-start / Hintergrundaktivität erlauben.
---
## Download
TV- und Mobile-Builds: [Releases](https://github.com/haumlab/hyperion-android-reborn/releases)
Siehe auch [CHANGELOG.md](CHANGELOG.md) und [PIPELINE_CHANGELOG.md](PIPELINE_CHANGELOG.md).
+2 -2
View File
@@ -13,8 +13,8 @@ android {
applicationId "com.hyperion.grabber" applicationId "com.hyperion.grabber"
minSdk 21 minSdk 21
targetSdk 34 targetSdk 34
versionCode 3000 versionCode 3001
versionName "3.0.0" versionName "3.0.1-mediacodec"
} }
buildTypes { buildTypes {
@@ -30,6 +30,7 @@ import android.widget.Toast;
import com.hyperion.grabber.common.BootActivity; import com.hyperion.grabber.common.BootActivity;
import com.hyperion.grabber.common.HyperionScreenService; import com.hyperion.grabber.common.HyperionScreenService;
import com.hyperion.grabber.common.util.MediaProjectionHelper;
import com.hyperion.grabber.common.util.PermissionHelper; import com.hyperion.grabber.common.util.PermissionHelper;
public class MainActivity extends AppCompatActivity implements ImageView.OnClickListener, public class MainActivity extends AppCompatActivity implements ImageView.OnClickListener,
@@ -151,7 +152,8 @@ public class MainActivity extends AppCompatActivity implements ImageView.OnClick
private void requestScreenCapture() { private void requestScreenCapture() {
try { try {
Intent captureIntent = mMediaProjectionManager.createScreenCaptureIntent(); Log.i(TAG, "Requesting MediaProjection permission (default display if API 34+)");
Intent captureIntent = MediaProjectionHelper.createCaptureIntent(mMediaProjectionManager);
startActivityForResult(captureIntent, REQUEST_MEDIA_PROJECTION); startActivityForResult(captureIntent, REQUEST_MEDIA_PROJECTION);
} catch (SecurityException e) { } catch (SecurityException e) {
Log.e(TAG, "Screen capture permission denied: " + e.getMessage()); Log.e(TAG, "Screen capture permission denied: " + e.getMessage());
@@ -29,6 +29,7 @@ import android.widget.Toast;
import com.hyperion.grabber.common.BootActivity; import com.hyperion.grabber.common.BootActivity;
import com.hyperion.grabber.common.HyperionScreenService; import com.hyperion.grabber.common.HyperionScreenService;
import com.hyperion.grabber.common.util.MediaProjectionHelper;
import com.hyperion.grabber.common.util.Preferences; import com.hyperion.grabber.common.util.Preferences;
import com.hyperion.grabber.R; import com.hyperion.grabber.R;
@@ -162,7 +163,8 @@ public class MainActivity extends LeanbackActivity implements ImageView.OnClickL
private void requestScreenCapture() { private void requestScreenCapture() {
try { try {
Intent captureIntent = mMediaProjectionManager.createScreenCaptureIntent(); Log.i(TAG, "Requesting MediaProjection permission (default display if API 34+)");
Intent captureIntent = MediaProjectionHelper.createCaptureIntent(mMediaProjectionManager);
startActivityForResult(captureIntent, REQUEST_MEDIA_PROJECTION); startActivityForResult(captureIntent, REQUEST_MEDIA_PROJECTION);
} catch (Exception e) { } catch (Exception e) {
Log.e(TAG, "Failed to request screen capture: " + e.getMessage()); Log.e(TAG, "Failed to request screen capture: " + e.getMessage());
@@ -217,7 +219,7 @@ public class MainActivity extends LeanbackActivity implements ImageView.OnClickL
} }
private void startSettings() { private void startSettings() {
stopScreenRecorder(); // Do not stop capture when opening settings — Home/settings must keep grabber alive.
Intent intent = new Intent(this, ManualSetupActivity.class); Intent intent = new Intent(this, ManualSetupActivity.class);
Bundle bundle = Bundle bundle =
ActivityOptionsCompat.makeSceneTransitionAnimation(this) ActivityOptionsCompat.makeSceneTransitionAnimation(this)
@@ -119,11 +119,15 @@ internal class BasicSettingsStepFragment : SettingsStepBaseFragment() {
val frameRateLabels = resources.getStringArray(CommonR.array.pref_list_framerate) val frameRateLabels = resources.getStringArray(CommonR.array.pref_list_framerate)
val frameRateValues = resources.getStringArray(CommonR.array.pref_list_framerate_values) val frameRateValues = resources.getStringArray(CommonR.array.pref_list_framerate_values)
val selectedCaptureRate = prefs.getString(CommonR.string.pref_key_framerate, "30") val storedCaptureRate = prefs.getString(CommonR.string.pref_key_framerate, "30") ?: "30"
val selectedCaptureRate =
if (frameRateValues.contains(storedCaptureRate)) storedCaptureRate else "30"
val captureRateDescription = val captureRateDescription =
if (prefs.contains(CommonR.string.pref_key_framerate)){ if (prefs.contains(CommonR.string.pref_key_framerate)
frameRateLabels[frameRateValues.indexOf(selectedCaptureRate)] && frameRateValues.contains(storedCaptureRate)) {
val idx = frameRateValues.indexOf(selectedCaptureRate)
frameRateLabels[idx]
} else { } else {
getString(CommonR.string.pref_summary_framerate) getString(CommonR.string.pref_summary_framerate)
} }
+1 -1
View File
@@ -8,7 +8,7 @@ buildscript {
mavenCentral() mavenCentral()
} }
dependencies { dependencies {
classpath 'com.android.tools.build:gradle:8.2.1' classpath 'com.android.tools.build:gradle:8.13.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong // NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files // in the individual module build.gradle files
@@ -6,12 +6,16 @@ import android.content.Intent;
import android.media.projection.MediaProjectionManager; import android.media.projection.MediaProjectionManager;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.util.Log;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi; import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatActivity;
import com.hyperion.grabber.common.util.MediaProjectionHelper;
public class BootActivity extends AppCompatActivity { public class BootActivity extends AppCompatActivity {
public static final int REQUEST_MEDIA_PROJECTION = 1; public static final int REQUEST_MEDIA_PROJECTION = 1;
private static final String TAG = "BootActivity";
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override @Override
@@ -20,7 +24,9 @@ public class BootActivity extends AppCompatActivity {
MediaProjectionManager manager = (MediaProjectionManager) MediaProjectionManager manager = (MediaProjectionManager)
getSystemService(Context.MEDIA_PROJECTION_SERVICE); getSystemService(Context.MEDIA_PROJECTION_SERVICE);
if (manager != null) { if (manager != null) {
startActivityForResult(manager.createScreenCaptureIntent(), REQUEST_MEDIA_PROJECTION); Log.i(TAG, "Requesting MediaProjection permission");
startActivityForResult(MediaProjectionHelper.createCaptureIntent(manager),
REQUEST_MEDIA_PROJECTION);
} else { } else {
finish(); finish();
} }
@@ -31,7 +37,10 @@ public class BootActivity extends AppCompatActivity {
super.onActivityResult(requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_MEDIA_PROJECTION) { if (requestCode == REQUEST_MEDIA_PROJECTION) {
if (resultCode == Activity.RESULT_OK) { if (resultCode == Activity.RESULT_OK) {
Log.i(TAG, "MediaProjection granted, starting service");
startScreenRecorder(this, resultCode, data); startScreenRecorder(this, resultCode, data);
} else {
Log.w(TAG, "MediaProjection denied resultCode=" + resultCode);
} }
finish(); finish();
} }
File diff suppressed because it is too large. Load diff
@@ -35,7 +35,7 @@ public class HyperionScreenService extends Service {
public static final String BROADCAST_ERROR = "SERVICE_ERROR"; public static final String BROADCAST_ERROR = "SERVICE_ERROR";
public static final String BROADCAST_TAG = "SERVICE_STATUS"; public static final String BROADCAST_TAG = "SERVICE_STATUS";
public static final String BROADCAST_FILTER = "SERVICE_FILTER"; public static final String BROADCAST_FILTER = "SERVICE_FILTER";
private static final boolean DEBUG = false; private static final boolean DEBUG = true;
private static final String TAG = "HyperionScreenService"; private static final String TAG = "HyperionScreenService";
private boolean mForegroundFailed = false; private boolean mForegroundFailed = false;
@@ -405,10 +405,15 @@ public class HyperionScreenService extends Service {
final DisplayMetrics metrics = new DisplayMetrics(); final DisplayMetrics metrics = new DisplayMetrics();
window.getDefaultDisplay().getRealMetrics(metrics); window.getDefaultDisplay().getRealMetrics(metrics);
Log.i(TAG, "MediaProjection OK screen=" + metrics.widthPixels + "x" + metrics.heightPixels
+ " dpi=" + metrics.densityDpi
+ " leds=" + mHorizontalLEDCount + "x" + mVerticalLEDCount
+ " fps=" + mFrameRate);
HyperionGrabberOptions options = new HyperionGrabberOptions( HyperionGrabberOptions options = new HyperionGrabberOptions(
mHorizontalLEDCount, mVerticalLEDCount, mFrameRate, mSendAverageColor); mHorizontalLEDCount, mVerticalLEDCount, mFrameRate, mSendAverageColor);
if (DEBUG) Log.v(TAG, "Creating encoder: " + metrics.widthPixels + "x" + metrics.heightPixels); Log.i(TAG, "Creating MediaCodec screen encoder");
mHyperionEncoder = new HyperionScreenEncoder( mHyperionEncoder = new HyperionScreenEncoder(
mHyperionThread.getReceiver(), mHyperionThread.getReceiver(),
projection, projection,
@@ -7,12 +7,16 @@ import android.content.Intent;
import android.media.projection.MediaProjectionManager; import android.media.projection.MediaProjectionManager;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.util.Log;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi; import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatActivity;
import com.hyperion.grabber.common.util.MediaProjectionHelper;
public class ToggleActivity extends AppCompatActivity { public class ToggleActivity extends AppCompatActivity {
public static final int REQUEST_MEDIA_PROJECTION = 1; public static final int REQUEST_MEDIA_PROJECTION = 1;
private static final String TAG = "ToggleActivity";
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override @Override
@@ -27,7 +31,6 @@ public class ToggleActivity extends AppCompatActivity {
} else { } else {
requestPermission(); requestPermission();
} }
} }
@Override @Override
@@ -35,11 +38,12 @@ public class ToggleActivity extends AppCompatActivity {
super.onActivityResult(requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_MEDIA_PROJECTION) { if (requestCode == REQUEST_MEDIA_PROJECTION) {
if (resultCode == Activity.RESULT_OK) { if (resultCode == Activity.RESULT_OK) {
Log.i(TAG, "MediaProjection granted");
startScreenRecorder(this, resultCode, data); startScreenRecorder(this, resultCode, data);
} else {
Log.w(TAG, "MediaProjection denied");
} }
finish(); finish();
} }
} }
@@ -79,17 +83,17 @@ public class ToggleActivity extends AppCompatActivity {
} }
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void requestPermission(){ private void requestPermission() {
MediaProjectionManager manager = (MediaProjectionManager) MediaProjectionManager manager = (MediaProjectionManager)
getSystemService(Context.MEDIA_PROJECTION_SERVICE); getSystemService(Context.MEDIA_PROJECTION_SERVICE);
if (manager != null) { if (manager != null) {
startActivityForResult(manager.createScreenCaptureIntent(), REQUEST_MEDIA_PROJECTION); Log.i(TAG, "Requesting MediaProjection permission");
startActivityForResult(MediaProjectionHelper.createCaptureIntent(manager),
REQUEST_MEDIA_PROJECTION);
} }
} }
/** stop recording & stop service */ private void stopService() {
private void stopService() {
Intent stopIntent = new Intent(ToggleActivity.this, HyperionScreenService.class); Intent stopIntent = new Intent(ToggleActivity.this, HyperionScreenService.class);
stopIntent.setAction(HyperionScreenService.ACTION_EXIT); stopIntent.setAction(HyperionScreenService.ACTION_EXIT);
startService(stopIntent); startService(stopIntent);
@@ -36,8 +36,10 @@ class HyperionThread(
val client = clientRef.get() val client = clientRef.get()
if (client == null || !client.isConnected()) return if (client == null || !client.isConnected()) return
// Copy — encoder reuses the ring buffer; async send must not share it.
val copy = data.copyOf()
++lastFrameNumber ++lastFrameNumber
latestFrame.set(FrameData(data, width, height, lastFrameNumber)) latestFrame.set(FrameData(copy, width, height, lastFrameNumber))
if (sendTaskScheduled.compareAndSet(false, true)) { if (sendTaskScheduled.compareAndSet(false, true)) {
networkExecutor.submit { sendLatestFrame() } networkExecutor.submit { sendLatestFrame() }
@@ -0,0 +1,36 @@
package com.hyperion.grabber.common.util;
import android.content.Intent;
import android.media.projection.MediaProjectionConfig;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.util.Log;
/**
* Creates MediaProjection consent intents. On Android 14+ prefers
* {@link MediaProjectionConfig#createConfigForDefaultDisplay()} so the entire
* display is captured (not only an app window).
*/
public final class MediaProjectionHelper {
private static final String TAG = "MediaProjectionHelper";
private MediaProjectionHelper() {}
public static Intent createCaptureIntent(MediaProjectionManager manager) {
if (manager == null) {
throw new IllegalArgumentException("MediaProjectionManager is null");
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
try {
MediaProjectionConfig config =
MediaProjectionConfig.createConfigForDefaultDisplay();
Log.i(TAG, "Using MediaProjectionConfig.createConfigForDefaultDisplay()");
return manager.createScreenCaptureIntent(config);
} catch (Exception e) {
Log.w(TAG, "Default-display config failed, falling back: " + e.getMessage());
}
}
Log.i(TAG, "Using default createScreenCaptureIntent()");
return manager.createScreenCaptureIntent();
}
}
@@ -7,59 +7,54 @@ import androidx.annotation.StringRes
import android.util.Log import android.util.Log
import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentHashMap
/** Wrapper around SharedPreferences which allows for default values defined in Resources /** Wrapper around SharedPreferences with defaults from Resources and an in-memory cache. */
* Main purpose is that defaults are defined in a centralized location and that preferences are
* accessed through a unified interface
* Now includes in-memory caching to reduce disk I/O */
class Preferences(context: Context) { class Preferences(context: Context) {
private val preferences = PreferenceManager.getDefaultSharedPreferences(context) private val preferences = PreferenceManager.getDefaultSharedPreferences(context)
private val resources = context.resources private val resources = context.resources
// In-memory cache to reduce SharedPreferences disk I/O // ConcurrentHashMap forbids null values — never store nulls.
private val stringCache = ConcurrentHashMap<String, String?>() private val stringCache = ConcurrentHashMap<String, String>()
private val intCache = ConcurrentHashMap<String, Int>() private val intCache = ConcurrentHashMap<String, Int>()
private val boolCache = ConcurrentHashMap<String, Boolean>() private val boolCache = ConcurrentHashMap<String, Boolean>()
private val cacheHits = ConcurrentHashMap<String, Boolean>() private val nullStringKeys = ConcurrentHashMap.newKeySet<String>()
fun contains(@StringRes keyResourceId: Int): Boolean = preferences.contains(key(keyResourceId)) fun contains(@StringRes keyResourceId: Int): Boolean = preferences.contains(key(keyResourceId))
fun getString(@StringRes keyResourceId: Int, default: String? = null): String? { fun getString(@StringRes keyResourceId: Int, default: String? = null): String? {
val keyStr = key(keyResourceId) val keyStr = key(keyResourceId)
// Return from cache if available if (nullStringKeys.contains(keyStr)) {
if (stringCache.containsKey(keyStr)) { return default
return stringCache[keyStr]
} }
stringCache[keyStr]?.let { return it }
// Fetch from SharedPreferences and cache
val value = preferences.getString(keyStr, default) val value = preferences.getString(keyStr, default)
stringCache[keyStr] = value if (value != null) {
stringCache[keyStr] = value
nullStringKeys.remove(keyStr)
} else {
stringCache.remove(keyStr)
nullStringKeys.add(keyStr)
}
return value return value
} }
fun putString(@StringRes keyResourceId: Int, value: String){ fun putString(@StringRes keyResourceId: Int, value: String) {
val keyStr = key(keyResourceId) val keyStr = key(keyResourceId)
val edit = preferences.edit() preferences.edit().putString(keyStr, value).apply()
edit.putString(keyStr, value)
edit.apply()
// Update cache
stringCache[keyStr] = value stringCache[keyStr] = value
nullStringKeys.remove(keyStr)
intCache.remove(keyStr) intCache.remove(keyStr)
boolCache.remove(keyStr) boolCache.remove(keyStr)
} }
fun getInt(@StringRes keyResourceId: Int): Int { fun getInt(@StringRes keyResourceId: Int): Int {
val keyStr = key(keyResourceId) val keyStr = key(keyResourceId)
intCache[keyStr]?.let { return it }
// Return from cache if available
if (intCache.containsKey(keyStr)) {
return intCache[keyStr]!!
}
val default = defaultKey(keyResourceId, "integer").let { val default = defaultKey(keyResourceId, "integer").let {
if (it == 0){ if (it == 0) {
0 0
} else { } else {
try { try {
@@ -75,33 +70,30 @@ class Preferences(context: Context) {
fun getInt(@StringRes keyResourceId: Int, default: Int = 0): Int { fun getInt(@StringRes keyResourceId: Int, default: Int = 0): Int {
val keyStr = key(keyResourceId) val keyStr = key(keyResourceId)
intCache[keyStr]?.let { return it }
// Return from cache if available val raw = getString(keyResourceId)
if (intCache.containsKey(keyStr)) { val value = try {
return intCache[keyStr]!! if (raw.isNullOrBlank()) default else Integer.parseInt(raw.trim())
} catch (e: NumberFormatException) {
Log.w("Preferences", "Invalid int for $keyStr: '$raw', using default $default")
default
} }
val value = getString(keyResourceId)?.let { Integer.parseInt(it) } ?: default
intCache[keyStr] = value intCache[keyStr] = value
return value return value
} }
fun putInt(@StringRes keyResourceId: Int, value: Int){ fun putInt(@StringRes keyResourceId: Int, value: Int) {
putString(keyResourceId, value.toString()) putString(keyResourceId, value.toString())
val keyStr = key(keyResourceId) intCache[key(keyResourceId)] = value
intCache[keyStr] = value
} }
fun getBoolean(@StringRes keyResourceId: Int): Boolean { fun getBoolean(@StringRes keyResourceId: Int): Boolean {
val keyStr = key(keyResourceId) val keyStr = key(keyResourceId)
boolCache[keyStr]?.let { return it }
// Return from cache if available
if (boolCache.containsKey(keyStr)) {
return boolCache[keyStr]!!
}
val default = defaultKey(keyResourceId, "bool").let { val default = defaultKey(keyResourceId, "bool").let {
if (it == 0){ if (it == 0) {
false false
} else { } else {
try { try {
@@ -119,46 +111,39 @@ class Preferences(context: Context) {
fun getBoolean(@StringRes keyResourceId: Int, default: Boolean): Boolean { fun getBoolean(@StringRes keyResourceId: Int, default: Boolean): Boolean {
val keyStr = key(keyResourceId) val keyStr = key(keyResourceId)
boolCache[keyStr]?.let { return it }
// Return from cache if available
if (boolCache.containsKey(keyStr)) {
return boolCache[keyStr]!!
}
val value = preferences.getBoolean(keyStr, default) val value = preferences.getBoolean(keyStr, default)
boolCache[keyStr] = value boolCache[keyStr] = value
return value return value
} }
fun putBoolean(@StringRes keyResourceId: Int, value: Boolean){ fun putBoolean(@StringRes keyResourceId: Int, value: Boolean) {
val keyStr = key(keyResourceId) val keyStr = key(keyResourceId)
val edit = preferences.edit() preferences.edit().putBoolean(keyStr, value).apply()
edit.putBoolean(keyStr, value)
edit.apply()
// Update cache
boolCache[keyStr] = value boolCache[keyStr] = value
stringCache.remove(keyStr) stringCache.remove(keyStr)
nullStringKeys.remove(keyStr)
intCache.remove(keyStr) intCache.remove(keyStr)
} }
/**
* Clears the in-memory cache but NOT the SharedPreferences
* Call this when you know preferences have been updated externally
*/
fun clearCache() { fun clearCache() {
stringCache.clear() stringCache.clear()
intCache.clear() intCache.clear()
boolCache.clear() boolCache.clear()
nullStringKeys.clear()
Log.d("Preferences", "Cache cleared") Log.d("Preferences", "Cache cleared")
} }
private fun key(keyResourceId: Int) = resources.getString(keyResourceId) private fun key(keyResourceId: Int) = resources.getString(keyResourceId)
/** @return 0 if not found, resource id otherwise */
private fun defaultKey(keyResourceId: Int, type: String): Int { private fun defaultKey(keyResourceId: Int, type: String): Int {
val defaultKeyName = resources.getResourceEntryName(keyResourceId).replace("pref_key_", "pref_default_") val defaultKeyName = resources.getResourceEntryName(keyResourceId)
return resources.getIdentifier(defaultKeyName, type, resources.getResourcePackageName(keyResourceId)) .replace("pref_key_", "pref_default_")
return resources.getIdentifier(
defaultKeyName,
type,
resources.getResourcePackageName(keyResourceId)
)
} }
} }
Binary file not shown.
+1 -1
View File
@@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-all.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-all.zip