Skip to content

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.

Follow-up to #296: the end of a rest sounds on time with the screen off on Android 14 and later, where the exact-alarm permission is no longer granted at install and the alarm came up to 50 seconds late: the countdown keeps the phone awake until the end and sounds it itself

Duarte Santos09a87f2c2f3f
diff --git a/docs/MOBILE.md b/docs/MOBILE.md
index 4cb2700c9..fb6d74fb6 100644
--- a/docs/MOBILE.md
+++ b/docs/MOBILE.md
@@ -213,6 +213,9 @@ membership, the distribution certificate and profile as protected file variables
service. `NOTICE.md` carries an app-store exception (an additional permission under
AGPL §7) granted by the copyright holder — relevant only if store distribution ever happens.
- The app requests notification permission when the workout-day reminder is switched on,
- and again for the rest-timer alarm if it is still unanswered. On Android it declares
- `SCHEDULE_EXACT_ALARM` so the reminder and the rest alert can fire on time with the
- screen locked, where the user allows exact alarms.
+ and again at the first rest if it is still unanswered. On Android it declares
+ `SCHEDULE_EXACT_ALARM` so the reminder fires to the minute where the user allows exact
+ alarms (Android 14 no longer grants it at install). The rest countdown does not depend on
+ it: a foreground service (`specialUse`) keeps the countdown in the notification and holds a
+ wake lock until the end, so the end of a rest sounds on time with the screen locked; the
+ rest-over alarm is only its fallback.
diff --git a/frontend/android/app/src/main/AndroidManifest.xml b/frontend/android/app/src/main/AndroidManifest.xml
index 09d3687dd..4774773f0 100644
--- a/frontend/android/app/src/main/AndroidManifest.xml
+++ b/frontend/android/app/src/main/AndroidManifest.xml
@@ -61,8 +61,12 @@
on Android 12+. Where it isn't granted, scheduling silently falls back to inexact
alarms — the reminder still arrives, just not to the minute. -->
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
- <!-- Same exact-alarm permission as the day reminder. Where it isn't granted, the rest
- alert falls back to an inexact alarm and, if this phone is paired, to Web Push. -->
+ <!-- Rest countdown (#296): the notification (asked for at the first rest on Android 13+),
+ the foreground service that keeps its clock, and the wake lock that lets that clock
+ reach the end on time with the screen off. The rest-over alarm uses the exact-alarm
+ permission above where it is granted; Android 14 no longer grants it at install, and
+ an inexact alarm can come most of a rest late, so the countdown sounds the end itself
+ and the alarm is only its fallback. -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<!-- The buzz at the end of a rest or a hold and on a set tick (navigator.vibrate). The
WebView drops every vibrate call from an app without this permission, so the phone
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.java
index 8fca2d3df..59b07454d 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
@@ -51,6 +51,7 @@ public final class RestAlert {
private static final long[] VIBRATE = new long[] {0, 200, 100, 200, 100, 400};
private static AudioTrack current;
+ private static long firedFor;
private RestAlert() {}
@@ -66,6 +67,7 @@ public final class RestAlert {
intent.putExtra("visibility", visibility == null ? "public" : visibility);
intent.putExtra("importance", importance == null ? "high" : importance);
intent.putExtra("localOnly", localOnly);
+ intent.putExtra("at", at);
PendingIntent pi = PendingIntent.getBroadcast(ctx, id, intent, FLAGS);
AlarmManager am = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
boolean exact = canExact(am);
@@ -76,7 +78,7 @@ public final class RestAlert {
am.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, pi);
exact = false;
}
- if (!exact) Log.w("openGym", "exact alarms not allowed; rest alert may be late with the screen off");
+ if (!exact) Log.w("openGym", "exact alarms not allowed; the rest countdown sounds the end itself");
if (Build.VERSION.SDK_INT >= 26) {
NotificationManager nm = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
ensureChannel(ctx, nm, channelId, importanceOf(importance), visibilityOf(visibility));
@@ -110,8 +112,33 @@ public final class RestAlert {
nm.cancel(id);
}
+ /**
+ * The countdown reached the end itself. Without the exact-alarm permission, which Android 14
+ * no longer grants at install, the alarm may be batched up to three quarters of the rest late
+ * (on an emulator it came 50 seconds after a 90-second rest), so the countdown sounds the end
+ * and the alarm is only the fallback for a countdown that was not running.
+ */
+ static void fireFromCountdown(Context ctx, long at) {
+ cancelAlarmOnly(ctx, NOTIFICATION_ID);
+ Intent intent = alarmIntent(ctx);
+ intent.putExtra("id", NOTIFICATION_ID);
+ intent.putExtra("title", lastAlertTitle);
+ intent.putExtra("sound", lastSound);
+ intent.putExtra("channelId", lastChannel);
+ intent.putExtra("at", at);
+ new Thread(() -> fire(ctx, intent), "opengym-rest").start();
+ }
+
+ /** One alert per end: the countdown and an exact alarm reach the same end in the same instant. */
+ private static synchronized boolean claim(long at) {
+ if (at > 0 && at == firedFor) return false;
+ firedFor = at;
+ return true;
+ }
+
/** Runs off the main thread. Holds the CPU until the tone has finished. */
public static void fire(Context ctx, Intent intent) {
+ if (!claim(intent.getLongExtra("at", 0))) return;
PowerManager.WakeLock cpu = null;
try {
PowerManager pm = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
@@ -130,12 +157,12 @@ public final class RestAlert {
pokeScreen(ctx);
boolean shown = showNotification(ctx, intent);
if (!shown) vibrateFallback(ctx);
- // Locked or in the background, the page cannot play its chime, so this is the one.
- boolean play = intent.getBooleanExtra("sound", true);
- if (play) playSound(ctx);
// The countdown card is the foreground-service notification. Drop it once the
// "rest over" alert is up, including when the WebView is frozen.
stopCountdown(ctx);
+ // Locked or in the background, the page cannot play its chime, so this is the one.
+ boolean play = intent.getBooleanExtra("sound", true);
+ if (play) playSound(ctx);
} finally {
if (cpu != null && cpu.isHeld()) cpu.release();
}
@@ -259,6 +286,7 @@ public final class RestAlert {
intent.putExtra("visibility", "public");
intent.putExtra("importance", "high");
intent.putExtra("localOnly", false);
+ intent.putExtra("at", at);
PendingIntent pi = PendingIntent.getBroadcast(ctx, NOTIFICATION_ID, intent, FLAGS);
AlarmManager am = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
try {
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.java
index d7b378280..c12901447 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
@@ -8,6 +8,7 @@ import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
+import android.os.PowerManager;
/**
* Foreground while a rest is running. Reposts one clock and one bar every second, and
@@ -27,12 +28,19 @@ public class RestTimerService extends Service {
private String skipLabel = "Skip";
private int accent = 0xFF30D158;
private int ink = 0xFF000000;
+ private PowerManager.WakeLock cpu;
private final Runnable tick = new Runnable() {
@Override
public void run() {
if (!running || paused || endsAt <= 0) return;
+ long left = endsAt - System.currentTimeMillis();
+ if (left <= 0) {
+ reachEnd();
+ return;
+ }
show();
- if (endsAt > System.currentTimeMillis()) handler.postDelayed(this, 1000);
+ // Next on the clock's next whole second, so the last run lands on the end itself.
+ handler.postDelayed(this, ((left - 1) % 1000) + 1);
}
};
@@ -88,6 +96,7 @@ public class RestTimerService extends Service {
totalMs = passed > 0 ? passed : Math.max(1000, endsAt - System.currentTimeMillis());
paused = false;
running = true;
+ holdCpuUntilEnd();
pauseLabel = text(intent, "pause", pauseLabel);
resumeLabel = text(intent, "resume", resumeLabel);
minusLabel = text(intent, "minus", minusLabel);
@@ -104,6 +113,7 @@ public class RestTimerService extends Service {
public void onDestroy() {
running = false;
handler.removeCallbacks(tick);
+ releaseCpu();
endsAt = 0;
stopForegroundCompat();
super.onDestroy();
@@ -114,10 +124,12 @@ public class RestTimerService extends Service {
pausedLeft = Math.max(0, endsAt - System.currentTimeMillis());
paused = true;
handler.removeCallbacks(tick);
+ releaseCpu();
RestAlert.cancelAlarmOnly(this, RestAlert.NOTIFICATION_ID);
} else {
endsAt = System.currentTimeMillis() + pausedLeft;
paused = false;
+ holdCpuUntilEnd();
RestAlert.updateAlarm(this, endsAt);
handler.removeCallbacks(tick);
tick.run();
@@ -137,6 +149,7 @@ public class RestTimerService extends Service {
pausedLeft = leftMs;
if (total > 0) totalMs = total;
handler.removeCallbacks(tick);
+ releaseCpu();
show();
}
@@ -154,6 +167,7 @@ public class RestTimerService extends Service {
if (paused) pausedLeft = left;
else {
endsAt = now + left;
+ holdCpuUntilEnd();
RestAlert.updateAlarm(this, endsAt);
handler.removeCallbacks(tick);
handler.post(tick);
@@ -162,9 +176,43 @@ public class RestTimerService extends Service {
emit("adjust");
}
+ /**
+ * 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.
+ */
+ private void reachEnd() {
+ running = false;
+ 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.
+ */
+ private void holdCpuUntilEnd() {
+ 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);
+ } catch (Exception ignored) { /* the alarm is still set */ }
+ }
+
+ private void releaseCpu() {
+ try {
+ if (cpu != null && cpu.isHeld()) cpu.release();
+ } catch (Exception ignored) { /* already released by its timeout */ }
+ }
+
private void finishSkip() {
running = false;
handler.removeCallbacks(tick);
+ releaseCpu();
RestAlert.cancelAlarmOnly(this, RestAlert.NOTIFICATION_ID);
RestAlertPlugin.emit("skip", 0, 0, 0, false);
stopForegroundCompat();