Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
perf(android): rest holds no wake lock when the exact alarm sounds the end; system draws the countdown clock
Duarte Santos3de16a3eab5f
diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlert.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlert.javaindex 6d91100f6..1f5290709 100644--- a/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlert.java+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlert.java@@ -16,6 +16,8 @@ import android.media.AudioFormat;import android.media.AudioTrack;import android.os.Build;import android.os.PowerManager;+import android.os.SystemClock;+import android.view.View;import android.os.VibrationAttributes;import android.os.VibrationEffect;import android.os.Vibrator;@@ -213,6 +215,15 @@ public final class RestAlert {return intent;}+ /** Whether the rest-over alarm is exact (and wakes the phone on time, also in Doze). */+ static boolean exactAllowed(Context ctx) {+ try {+ return canExact((AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE));+ } catch (Exception e) {+ return false;+ }+ }+private static boolean canExact(AlarmManager am) {if (Build.VERSION.SDK_INT < 31) return true;return am.canScheduleExactAlarms();@@ -429,10 +440,14 @@ public final class RestAlert {String clock = clock(left);NotificationManager nm = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);ensureCountdownChannel(ctx, nm);+ // Running: the system counts the clock down itself (Chronometer), so the card needs no+ // repost per second for the time. Paused: a plain text, which cannot drift when the+ // shade redraws the card later.+ long base = paused ? 0 : RestCountdownPlan.chronometerBase(SystemClock.elapsedRealtime(), leftMs);RemoteViews compact = new RemoteViews(ctx.getPackageName(), R.layout.rest_countdown);- fillClock(compact, clock, max, left, accent);+ fillClock(compact, clock, max, left, accent, paused, base);RemoteViews expanded = new RemoteViews(ctx.getPackageName(), R.layout.rest_countdown_big);- fillClock(expanded, clock, max, left, accent);+ fillClock(expanded, clock, max, left, accent, paused, base);applyAccent(expanded, accent, ink);expanded.setTextViewText(R.id.rest_pause, paused ? resume : pause);expanded.setTextViewText(R.id.rest_minus, minus);@@ -472,8 +487,17 @@ public final class RestAlert {return b.build();}- private static void fillClock(RemoteViews views, String clock, int max, int left, int accent) {+ private static void fillClock(RemoteViews views, String clock, int max, int left, int accent,+ boolean paused, long base) {views.setTextViewText(R.id.rest_clock, clock);+ views.setViewVisibility(R.id.rest_clock, paused ? View.VISIBLE : View.GONE);+ views.setViewVisibility(R.id.rest_chrono, paused ? View.GONE : View.VISIBLE);+ if (!paused) {+ views.setChronometer(R.id.rest_chrono, base, null, true);+ views.setChronometerCountDown(R.id.rest_chrono, true);+ } else {+ views.setChronometer(R.id.rest_chrono, 0, null, false);+ }views.setProgressBar(R.id.rest_bar, max, left, false);if (Build.VERSION.SDK_INT >= 31) {views.setColorStateList(R.id.rest_bar, "setProgressTintList", ColorStateList.valueOf(accent));diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestCountdownPlan.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestCountdownPlan.javanew file mode 100644index 000000000..08733a842--- /dev/null+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestCountdownPlan.java@@ -0,0 +1,57 @@+package ch.duartesantos.opengym;++/**+ * The battery side of the rest countdown, kept free of Android classes so it is unit tested.+ *+ * The clock in the countdown card is a Chronometer that the system draws itself, so the card is+ * reposted only for the bar, and only while someone can see it (screen on). With the screen off+ * nothing is reposted, and turning the screen on brings the card up to date at once.+ *+ * The end is sounded by an exact alarm where Android allows one: that alarm wakes the phone,+ * also in Doze, and RestAlert.fire holds the CPU for the few seconds of the alert. The countdown+ * then holds no wake lock during the rest. Without the exact-alarm permission the alarm may come+ * most of a rest late, so the countdown keeps the CPU awake to sound the end on time, as before.+ */+final class RestCountdownPlan {+ /** Held past the end so the alert can take over before this lock runs out. */+ static final long END_GRACE_MS = 10_000;++ private RestCountdownPlan() {}++ /** How long the countdown holds the CPU for a rest with `leftMs` to go; 0 = no lock at all. */+ static long cpuHoldMs(boolean exactAlarm, long leftMs) {+ if (exactAlarm) return 0;+ return Math.max(0, leftMs) + END_GRACE_MS;+ }++ /**+ * Delay to the next run of the countdown loop. With the screen on, the next whole second so+ * the bar moves with the clock and the last run lands on the end itself. With the screen off+ * nothing is drawn, so the loop only wakes for the end.+ */+ static long nextTickMs(long leftMs, boolean interactive) {+ if (leftMs <= 0) return 0;+ if (!interactive) return leftMs;+ return ((leftMs - 1) % 1000) + 1;+ }++ /**+ * Chronometer base (elapsed-realtime clock) for a countdown with `leftMs` to go. The+ * Chronometer shows whole seconds rounded down; +999 makes it round up like the in-app clock+ * (and RestAlert.clock), so 1:30 is shown for the whole first second of a 90 s rest and+ * 0:00 at the end.+ */+ static long chronometerBase(long elapsedNow, long leftMs) {+ return elapsedNow + Math.max(0, leftMs) + 999;+ }++ /** Seconds a Chronometer counting down to `base` shows at `elapsedNow` (its own rounding). */+ static long chronometerShows(long base, long elapsedNow) {+ return (base - elapsedNow) / 1000;+ }++ /** The in-app clock's seconds for `leftMs` (round up), what the card used to print. */+ static long clockSeconds(long leftMs) {+ return (Math.max(0, leftMs) + 999) / 1000;+ }+}diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestTimerService.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestTimerService.javaindex c96daa6a1..f8150d7b1 100644--- a/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestTimerService.java+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestTimerService.java@@ -2,7 +2,10 @@ package ch.duartesantos.opengym;import android.app.Notification;import android.app.Service;+import android.content.BroadcastReceiver;+import android.content.Context;import android.content.Intent;+import android.content.IntentFilter;import android.content.pm.ServiceInfo;import android.os.Build;import android.os.Handler;@@ -11,8 +14,9 @@ import android.os.Looper;import android.os.PowerManager;/**- * Foreground while a rest is running. Reposts one clock and one bar every second, and- * applies the same controls as the in-app timer: pause, −15s, +15s, skip.+ * Foreground while a rest is running. Shows one clock and one bar, and applies the same controls+ * as the in-app timer: pause, −15s, +15s, skip. The clock is a Chronometer the system runs; the+ * card is reposted every second only while the screen is on (for the bar), see RestCountdownPlan.*/public class RestTimerService extends Service {private final Handler handler = new Handler(Looper.getMainLooper());@@ -29,6 +33,8 @@ public class RestTimerService extends Service {private int accent = 0xFF30D158;private int ink = 0xFF000000;private PowerManager.WakeLock cpu;+ private PowerManager power;+ private BroadcastReceiver screenOn;private final Runnable tick = new Runnable() {@Overridepublic void run() {@@ -38,12 +44,43 @@ public class RestTimerService extends Service {reachEnd();return;}- show();- // Next on the clock's next whole second, so the last run lands on the end itself.- handler.postDelayed(this, ((left - 1) % 1000) + 1);+ // Screen off: nobody sees the card, and the Chronometer keeps the clock right anyway.+ // Turning the screen on runs this loop at once (screenOn), so the bar catches up.+ boolean interactive = interactive();+ if (interactive) show();+ handler.postDelayed(this, RestCountdownPlan.nextTickMs(left, interactive));}};+ @Override+ public void onCreate() {+ super.onCreate();+ power = (PowerManager) getSystemService(POWER_SERVICE);+ screenOn = new BroadcastReceiver() {+ @Override+ public void onReceive(Context context, Intent intent) {+ if (!running || paused) return;+ handler.removeCallbacks(tick);+ tick.run();+ }+ };+ try {+ IntentFilter f = new IntentFilter(Intent.ACTION_SCREEN_ON);+ if (Build.VERSION.SDK_INT >= 33) registerReceiver(screenOn, f, Context.RECEIVER_NOT_EXPORTED);+ else registerReceiver(screenOn, f);+ } catch (Exception e) {+ screenOn = null;+ }+ }++ private boolean interactive() {+ try {+ return power == null || power.isInteractive();+ } catch (Exception e) {+ return true;+ }+ }+@Overridepublic IBinder onBind(Intent intent) {return null;@@ -106,6 +143,8 @@ public class RestTimerService extends Service {if (intent != null && intent.hasExtra("ink")) ink = intent.getIntExtra("ink", ink);handler.removeCallbacks(tick);tick.run();+ // A foreground service must post its card now, whether or not the screen is on.+ if (running && !interactive()) show();return START_NOT_STICKY;}@@ -114,6 +153,10 @@ public class RestTimerService extends Service {running = false;handler.removeCallbacks(tick);releaseCpu();+ if (screenOn != null) {+ try { unregisterReceiver(screenOn); } catch (Exception ignored) { /* not registered */ }+ screenOn = null;+ }endsAt = 0;stopForegroundCompat();super.onDestroy();@@ -178,31 +221,51 @@ public class RestTimerService extends Service {/*** The end, reached by this countdown. The alert (or, with the app on screen, just the end of- * this card) comes from RestAlert, which stops this service once it is up. The CPU stays held- * until then: letting go here could let the phone sleep before that alert holds its own.+ * this card) comes from RestAlert, which stops this service once it is up. The CPU is held+ * until then (a short lock when the rest itself held none): letting go here could let the+ * phone sleep before that alert holds its own, with the alarm already called off.*/private void reachEnd() {running = false;+ holdCpuBriefly();RestAlert.fireFromCountdown(getApplicationContext(), endsAt);}/**- * Keeps the CPU running until the end, and ten seconds past it. With the screen off a phone- * otherwise sleeps through this countdown's last second, and the only thing left to wake it- * is the alarm, which without the exact-alarm permission comes late. Released on pause,- * on skip and when the service stops after the end, so a held rest costs nothing.+ * With exact alarms allowed, the alarm wakes the phone at the end (also in Doze) and+ * RestAlert.fire holds the CPU for the alert, so the rest itself holds nothing. Without+ * them the alarm may come most of a rest late: then the CPU is kept running until the end,+ * and ten seconds past it, so this countdown sounds the end on time with the screen off.+ * Released on pause, on skip and when the service stops after the end.*/private void holdCpuUntilEnd() {+ long hold = RestCountdownPlan.cpuHoldMs(+ RestAlert.exactAllowed(this), endsAt - System.currentTimeMillis());+ if (hold <= 0) {+ releaseCpu();+ return;+ }try {if (cpu == null) {PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);cpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "opengym:rest-countdown");cpu.setReferenceCounted(false);}- cpu.acquire(Math.max(0, endsAt - System.currentTimeMillis()) + 10_000);+ cpu.acquire(hold);} catch (Exception ignored) { /* the alarm is still set */ }}+ private void holdCpuBriefly() {+ try {+ if (cpu == null) {+ PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);+ cpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "opengym:rest-countdown");+ cpu.setReferenceCounted(false);+ }+ if (!cpu.isHeld()) cpu.acquire(RestCountdownPlan.END_GRACE_MS);+ } catch (Exception ignored) { /* the alert takes its own */ }+ }+private void releaseCpu() {try {if (cpu != null && cpu.isHeld()) cpu.release();diff --git a/frontend/android/app/src/main/res/layout/rest_countdown.xml b/frontend/android/app/src/main/res/layout/rest_countdown.xmlindex 45696ec20..a7fc85a22 100644--- a/frontend/android/app/src/main/res/layout/rest_countdown.xml+++ b/frontend/android/app/src/main/res/layout/rest_countdown.xml@@ -16,6 +16,20 @@android:textSize="22sp"android:textStyle="bold" />+ <!-- Running: the system counts this down itself (no repost per second). The TextView+ above shows the time only while paused. -->+ <Chronometer+ android:id="@+id/rest_chrono"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:countDown="true"+ android:fontFeatureSettings="tnum"+ android:minWidth="52dp"+ android:textAppearance="@android:style/TextAppearance.Material.Notification.Title"+ android:textSize="22sp"+ android:textStyle="bold"+ android:visibility="gone" />+<ProgressBarandroid:id="@+id/rest_bar"style="?android:attr/progressBarStyleHorizontal"diff --git a/frontend/android/app/src/main/res/layout/rest_countdown_big.xml b/frontend/android/app/src/main/res/layout/rest_countdown_big.xmlindex c25c0094a..8efbaab96 100644--- a/frontend/android/app/src/main/res/layout/rest_countdown_big.xml+++ b/frontend/android/app/src/main/res/layout/rest_countdown_big.xml@@ -22,6 +22,20 @@android:textSize="26sp"android:textStyle="bold" />+ <!-- Running: the system counts this down itself (no repost per second). The TextView+ above shows the time only while paused. -->+ <Chronometer+ android:id="@+id/rest_chrono"+ android:layout_width="wrap_content"+ android:layout_height="wrap_content"+ android:countDown="true"+ android:fontFeatureSettings="tnum"+ android:minWidth="58dp"+ android:textAppearance="@android:style/TextAppearance.Material.Notification.Title"+ android:textSize="26sp"+ android:textStyle="bold"+ android:visibility="gone" />+<ProgressBarandroid:id="@+id/rest_bar"style="?android:attr/progressBarStyleHorizontal"diff --git a/frontend/android/app/src/test/java/ch/duartesantos/opengym/RestCountdownPlanTest.java b/frontend/android/app/src/test/java/ch/duartesantos/opengym/RestCountdownPlanTest.javanew file mode 100644index 000000000..6e1995ced--- /dev/null+++ b/frontend/android/app/src/test/java/ch/duartesantos/opengym/RestCountdownPlanTest.java@@ -0,0 +1,66 @@+package ch.duartesantos.opengym;++import static org.junit.Assert.*;++import org.junit.Test;++/** The rest countdown's battery plan (RestCountdownPlan): wake lock, loop and Chronometer. */+public class RestCountdownPlanTest {+ @Test+ public void exactAlarmMeansNoWakeLockDuringTheRest() {+ assertEquals(0, RestCountdownPlan.cpuHoldMs(true, 90_000));+ assertEquals(0, RestCountdownPlan.cpuHoldMs(true, 0));+ }++ @Test+ public void withoutExactAlarmsTheCpuIsHeldToTheEndAndTenSecondsPast() {+ assertEquals(100_000, RestCountdownPlan.cpuHoldMs(false, 90_000));+ assertEquals(10_000, RestCountdownPlan.cpuHoldMs(false, -500));+ }++ @Test+ public void screenOnTicksOnWholeSecondsAndLandsOnTheEnd() {+ assertEquals(1000, RestCountdownPlan.nextTickMs(90_000, true));+ assertEquals(500, RestCountdownPlan.nextTickMs(89_500, true));+ assertEquals(1, RestCountdownPlan.nextTickMs(1, true));+ // Walk a whole 90 s rest: 90 runs, the last exactly on the end.+ long left = 90_000;+ int runs = 0;+ while (left > 0) {+ left -= RestCountdownPlan.nextTickMs(left, true);+ runs++;+ }+ assertEquals(90, runs);+ assertEquals(0, left);+ }++ @Test+ public void screenOffWakesOnlyForTheEnd() {+ assertEquals(90_000, RestCountdownPlan.nextTickMs(90_000, false));+ assertEquals(0, RestCountdownPlan.nextTickMs(0, false));+ }++ @Test+ public void chronometerShowsWhatTheOldClockPrinted() {+ long now = 5_000_000;+ for (long total : new long[] {1_000, 45_000, 90_000, 180_000, 61_500}) {+ long base = RestCountdownPlan.chronometerBase(now, total);+ // Every 10 ms of the rest, the Chronometer and the in-app clock agree.+ for (long passed = 0; passed <= total; passed += 10) {+ long left = total - passed;+ assertEquals("total " + total + " passed " + passed,+ RestCountdownPlan.clockSeconds(left),+ RestCountdownPlan.chronometerShows(base, now + passed));+ }+ }+ }++ @Test+ public void chronometerOfA90sRestStartsAt1_30AndEndsAt0_00() {+ long base = RestCountdownPlan.chronometerBase(0, 90_000);+ assertEquals("1:30", RestAlert.clock((int) RestCountdownPlan.chronometerShows(base, 0)));+ assertEquals("1:30", RestAlert.clock((int) RestCountdownPlan.chronometerShows(base, 999)));+ assertEquals("1:29", RestAlert.clock((int) RestCountdownPlan.chronometerShows(base, 1000)));+ assertEquals("0:00", RestAlert.clock((int) RestCountdownPlan.chronometerShows(base, 90_000)));+ }+}