Implement a bunch of features for alarm reliability

This commit is contained in:
James Babcock committed 2026-09-04 02:24:02 -07:00
1 parent f601a62c75
commit 74199390d2
18 files changed
+2011 -282

No files matched your search

@@ -25,7 +25,17 @@
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation"/>
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM"/>
<!-- Alarm clock reliability (Timers app): USE_EXACT_ALARM is granted
outright on Android 13+ for alarm-clock apps and cannot be revoked
by accident; SCHEDULE_EXACT_ALARM covers Android 12. The receiver
re-arms alarms after reboots; the ringing service plays on the alarm
stream and shows a full-screen alarm over the lock screen. -->
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" android:maxSdkVersion="32"/>
<uses-permission android:name="android.permission.USE_EXACT_ALARM"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK"/>
<uses-permission android:name="android.permission.READ_CALENDAR"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
@@ -127,10 +137,40 @@
<data android:scheme="wear" android:host="*" android:pathPrefix="/" />
</intent-filter>
</service>
<!-- Timers app alarm clock: the AlarmManager target, the reboot /
time-change rescheduler, the ringing foreground service, and the
lock-screen ringing activity. All Java, so alarms ring with the
JavaScript side asleep or gone. -->
<receiver
android:name="com.faceclaw.app.FaceclawTimerReceiver"
android:name="com.faceclaw.app.FaceclawAlarmReceiver"
android:enabled="true"
android:exported="false" />
<receiver
android:name="com.faceclaw.app.FaceclawAlarmRescheduleReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
<action android:name="android.intent.action.TIME_SET" />
<action android:name="android.intent.action.TIMEZONE_CHANGED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
<service
android:name="com.faceclaw.app.FaceclawAlarmService"
android:enabled="true"
android:exported="false"
android:foregroundServiceType="mediaPlayback" />
<activity
android:name="com.faceclaw.app.FaceclawAlarmActivity"
android:exported="false"
android:excludeFromRecents="true"
android:launchMode="singleInstance"
android:showWhenLocked="true"
android:turnScreenOn="true"
android:theme="@android:style/Theme.Material.NoActionBar" />
<!-- adb-only settings export/import (see FaceclawSettingsPortReceiver).
DUMP is a development permission: the adb shell holds it, other
apps cannot get it granted without adb, so this stays reachable
@@ -0,0 +1,181 @@
package com.faceclaw.app;
import android.app.Activity;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
/**
* The phone's ringing screen: shown over the lock screen by the alarm
* notification's full-screen intent (or by tapping the notification). Pure
* Java, so it works with the JavaScript side asleep or gone. Snooze and
* Dismiss go to the service, which journals them for the engine.
*/
public class FaceclawAlarmActivity extends Activity {
private final Handler handler = new Handler(Looper.getMainLooper());
private TextView titleView;
private TextView textView;
private TextView timeView;
private Button snoozeButton;
private long itemId;
private final Runnable poll = new Runnable() {
@Override
public void run() {
List<FaceclawAlarmService.Ringing> items = FaceclawAlarmService.snapshot();
if (items.isEmpty()) {
finish();
return;
}
FaceclawAlarmService.Ringing shown = null;
for (FaceclawAlarmService.Ringing item : items) {
if (item.id == itemId) {
shown = item;
}
}
if (shown == null) {
shown = items.get(0);
itemId = shown.id;
}
render(shown, items.size());
handler.postDelayed(this, 1000);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
showOverLockScreen();
itemId = getIntent() == null ? 0 : getIntent().getLongExtra(FaceclawAlarms.EXTRA_ID, 0);
setContentView(buildLayout());
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
itemId = intent == null ? 0 : intent.getLongExtra(FaceclawAlarms.EXTRA_ID, 0);
}
@Override
protected void onResume() {
super.onResume();
handler.post(poll);
}
@Override
protected void onPause() {
handler.removeCallbacks(poll);
super.onPause();
}
private void showOverLockScreen() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
setShowWhenLocked(true);
setTurnScreenOn(true);
KeyguardManager keyguard = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
if (keyguard != null) {
keyguard.requestDismissKeyguard(this, null);
}
} else {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
}
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
private View buildLayout() {
LinearLayout root = new LinearLayout(this);
root.setOrientation(LinearLayout.VERTICAL);
root.setGravity(Gravity.CENTER);
root.setBackgroundColor(Color.BLACK);
int pad = dp(32);
root.setPadding(pad, pad, pad, pad);
timeView = new TextView(this);
timeView.setTextColor(Color.WHITE);
timeView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 64);
timeView.setTypeface(Typeface.DEFAULT_BOLD);
timeView.setGravity(Gravity.CENTER);
root.addView(timeView, wrap());
titleView = new TextView(this);
titleView.setTextColor(Color.WHITE);
titleView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 28);
titleView.setGravity(Gravity.CENTER);
titleView.setPadding(0, dp(16), 0, 0);
root.addView(titleView, wrap());
textView = new TextView(this);
textView.setTextColor(Color.LTGRAY);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
textView.setGravity(Gravity.CENTER);
textView.setPadding(0, dp(8), 0, dp(40));
root.addView(textView, wrap());
snoozeButton = new Button(this);
snoozeButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
snoozeButton.setOnClickListener(view -> act(FaceclawAlarmService.ACTION_SNOOZE));
root.addView(snoozeButton, button());
Button dismissButton = new Button(this);
dismissButton.setText("Dismiss");
dismissButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
dismissButton.setOnClickListener(view -> act(FaceclawAlarmService.ACTION_DISMISS));
root.addView(dismissButton, button());
return root;
}
private void render(FaceclawAlarmService.Ringing item, int count) {
timeView.setText(DateFormat.getTimeInstance(DateFormat.SHORT).format(new Date()));
titleView.setText(count > 1 ? item.title + " (+" + (count - 1) + " more)" : item.title);
String status = item.silenced ? "Not answered" : item.escalated ? "" : "Ringing on the glasses";
textView.setText(item.text.isEmpty() ? status : status.isEmpty() ? item.text : item.text + "\n" + status);
snoozeButton.setText(FaceclawAlarms.KIND_TIMER.equals(item.kind)
? "+" + item.snoozeMinutes + " min"
: "Snooze " + item.snoozeMinutes + " min");
}
/** Apply the action to every ringing item (one tap silences the phone). */
private void act(String action) {
for (FaceclawAlarmService.Ringing item : FaceclawAlarmService.snapshot()) {
Intent intent = new Intent(this, FaceclawAlarmService.class)
.setAction(action)
.putExtra(FaceclawAlarms.EXTRA_ID, item.id);
startService(intent);
}
finish();
}
private LinearLayout.LayoutParams wrap() {
return new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
}
private LinearLayout.LayoutParams button() {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, dp(64));
params.topMargin = dp(12);
return params;
}
private int dp(int value) {
return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, getResources().getDisplayMetrics()));
}
}
@@ -0,0 +1,6 @@
package com.faceclaw.app;
/** Phone-side alarm actions (dismiss / snooze), delivered to the JS engine; implemented in JS. */
public interface FaceclawAlarmListener {
void onPhoneAction(long id, String action, int minutes);
}
@@ -0,0 +1,27 @@
package com.faceclaw.app;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/** The AlarmManager target: an item came due, start the ringing service. */
public class FaceclawAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent == null || !FaceclawAlarms.ACTION_EXPIRE.equals(intent.getAction())) {
return;
}
long id = intent.getLongExtra(FaceclawAlarms.EXTRA_ID, 0);
if (id == 0) {
return;
}
FaceclawAlarmService.ring(
context.getApplicationContext(),
id,
intent.getStringExtra(FaceclawAlarms.EXTRA_TITLE),
intent.getStringExtra(FaceclawAlarms.EXTRA_TEXT),
intent.getStringExtra(FaceclawAlarms.EXTRA_KIND),
intent.getIntExtra(FaceclawAlarms.EXTRA_SNOOZE_MINUTES, 10)
);
}
}
@@ -0,0 +1,34 @@
package com.faceclaw.app;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/**
* Re-arms the persisted alarm schedule when the system would otherwise have
* dropped it: after a reboot (AlarmManager alarms do not survive one), a
* package update, or a wall-clock / time-zone change. Runs without the
* JavaScript side; only the device-protected schedule file is needed.
*/
public class FaceclawAlarmRescheduleReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent == null ? null : intent.getAction();
if (action == null) {
return;
}
switch (action) {
case Intent.ACTION_BOOT_COMPLETED:
case Intent.ACTION_LOCKED_BOOT_COMPLETED:
case Intent.ACTION_MY_PACKAGE_REPLACED:
case Intent.ACTION_TIME_CHANGED:
case Intent.ACTION_TIMEZONE_CHANGED:
case "android.intent.action.QUICKBOOT_POWERON":
case "com.htc.intent.action.QUICKBOOT_POWERON":
FaceclawAlarms.rescheduleAll(context, action);
break;
default:
break;
}
}
}
@@ -0,0 +1,649 @@
package com.faceclaw.app;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ServiceInfo;
import android.media.AudioAttributes;
import android.media.AudioFocusRequest;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.PowerManager;
import android.os.VibrationEffect;
import android.os.Vibrator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* The ringing foreground service. One instance carries every item currently
* ringing. Each item starts silent on the phone (a heads-up / lock-screen
* notification only, the glasses do the ringing) and escalates to phone
* sound and vibration when the glasses cannot carry it: not connected, not
* on a head, charging, no delivery confirmation from the JS side within a
* few seconds, or no acknowledgement within 30 seconds of delivery. Sound
* uses the alarm stream, so media volume, the ringer switch and (unless set
* to total silence) Do Not Disturb do not silence it.
*/
public class FaceclawAlarmService extends Service {
public static final String CHANNEL_ID = "faceclaw-alarms";
static final String ACTION_RING = "com.faceclaw.app.action.ALARM_RING";
static final String ACTION_DELIVERED = "com.faceclaw.app.action.ALARM_DELIVERED";
static final String ACTION_DISMISS = "com.faceclaw.app.action.ALARM_DISMISS";
static final String ACTION_SNOOZE = "com.faceclaw.app.action.ALARM_SNOOZE";
/** Stop an item quietly (acknowledged on the glasses / cancelled by the engine). */
static final String ACTION_STOP_ITEM = "com.faceclaw.app.action.ALARM_STOP_ITEM";
/** How long to wait for the JS side to confirm the glasses are showing the item. */
static final long DELIVERY_WAIT_MS = 5_000L;
/** How long after delivery to the glasses before the phone joins in. */
static final long ACK_WAIT_MS = 30_000L;
/** Sound and vibration stop after this; the notification stays. */
static final long AUTO_SILENCE_MS = 10 * 60_000L;
/** Alarm-stream level (fraction of max) used when the wearer has it muted. */
static final float MUTED_VOLUME_FRACTION = 0.6f;
static final class Ringing {
final long id;
final String title;
final String text;
final String kind;
final int snoozeMinutes;
final long ringAtMs;
long deliveredAtMs;
boolean escalated;
boolean silenced;
Ringing(long id, String title, String text, String kind, int snoozeMinutes) {
this.id = id;
this.title = title == null || title.trim().isEmpty() ? "Alarm" : title;
this.text = text == null ? "" : text;
this.kind = kind == null ? FaceclawAlarms.KIND_ALARM : kind;
this.snoozeMinutes = Math.max(1, snoozeMinutes);
this.ringAtMs = System.currentTimeMillis();
}
}
/** Ringing items, oldest first; static so the activity can read them. */
private static final Map<Long, Ringing> ringing = Collections.synchronizedMap(new LinkedHashMap<>());
/**
* Signals that arrived before the ring intent was processed (the JS
* engine fires, launches its window and reports delivery on the same
* main thread the service's onStartCommand queues behind), keyed by id
* with their arrival time. Consumed by startRinging.
*/
private static final Map<Long, Long> deliveredEarly = Collections.synchronizedMap(new LinkedHashMap<>());
private static final Map<Long, Long> stoppedEarly = Collections.synchronizedMap(new LinkedHashMap<>());
private static final long EARLY_SIGNAL_MAX_AGE_MS = 15_000L;
private final Handler handler = new Handler(Looper.getMainLooper());
private MediaPlayer player;
private Vibrator vibrator;
private PowerManager.WakeLock wakeLock;
private AudioManager audioManager;
private AudioFocusRequest focusRequest;
private int restoreAlarmVolume = -1;
private long foregroundId;
// ------------------------------------------------------------------
// Static entry points
public static void ring(Context context, long id, String title, String text, String kind, int snoozeMinutes) {
Context appContext = context.getApplicationContext();
Intent intent = new Intent(appContext, FaceclawAlarmService.class)
.setAction(ACTION_RING)
.putExtra(FaceclawAlarms.EXTRA_ID, id)
.putExtra(FaceclawAlarms.EXTRA_TITLE, title)
.putExtra(FaceclawAlarms.EXTRA_TEXT, text)
.putExtra(FaceclawAlarms.EXTRA_KIND, kind)
.putExtra(FaceclawAlarms.EXTRA_SNOOZE_MINUTES, snoozeMinutes);
FaceclawAlarms.startServiceCompat(appContext, intent);
}
public static void delivered(Context context, long id) {
if (!ringing.containsKey(id)) {
deliveredEarly.put(id, System.currentTimeMillis());
return;
}
Context appContext = context.getApplicationContext();
appContext.startService(new Intent(appContext, FaceclawAlarmService.class)
.setAction(ACTION_DELIVERED)
.putExtra(FaceclawAlarms.EXTRA_ID, id));
}
public static void stopItem(Context context, long id) {
if (!ringing.containsKey(id)) {
stoppedEarly.put(id, System.currentTimeMillis());
return;
}
Context appContext = context.getApplicationContext();
appContext.startService(new Intent(appContext, FaceclawAlarmService.class)
.setAction(ACTION_STOP_ITEM)
.putExtra(FaceclawAlarms.EXTRA_ID, id));
}
public static boolean isRinging(long id) {
return ringing.containsKey(id);
}
public static boolean isAnythingRinging() {
return !ringing.isEmpty();
}
static List<Ringing> snapshot() {
synchronized (ringing) {
return new ArrayList<>(ringing.values());
}
}
static PendingIntent actionIntent(Context appContext, String action, long id) {
Intent intent = new Intent(appContext, FaceclawAlarmService.class)
.setAction(action)
.putExtra(FaceclawAlarms.EXTRA_ID, id);
int flags = PendingIntent.FLAG_UPDATE_CURRENT;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
flags |= PendingIntent.FLAG_IMMUTABLE;
}
int code = FaceclawAlarms.requestCode(id) ^ action.hashCode();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
return PendingIntent.getForegroundService(appContext, code, intent, flags);
}
return PendingIntent.getService(appContext, code, intent, flags);
}
// ------------------------------------------------------------------
// Service lifecycle
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String action = intent == null ? null : intent.getAction();
long id = intent == null ? 0 : intent.getLongExtra(FaceclawAlarms.EXTRA_ID, 0);
if (action == null) {
// Restarted by the system with nothing to do.
finishIfIdle();
return START_NOT_STICKY;
}
switch (action) {
case ACTION_RING:
startRinging(new Ringing(
id,
intent.getStringExtra(FaceclawAlarms.EXTRA_TITLE),
intent.getStringExtra(FaceclawAlarms.EXTRA_TEXT),
intent.getStringExtra(FaceclawAlarms.EXTRA_KIND),
intent.getIntExtra(FaceclawAlarms.EXTRA_SNOOZE_MINUTES, 10)
));
break;
case ACTION_DELIVERED:
markDelivered(id);
break;
case ACTION_DISMISS:
dismiss(id);
break;
case ACTION_SNOOZE:
snooze(id);
break;
case ACTION_STOP_ITEM:
stopItemQuietly(id, "acknowledged");
break;
default:
break;
}
finishIfIdle();
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
handler.removeCallbacksAndMessages(null);
stopSound();
releaseWakeLock();
super.onDestroy();
}
// ------------------------------------------------------------------
// Ringing
private void startRinging(Ringing item) {
if (item.id == 0) {
return;
}
ensureChannel();
Ringing existing = ringing.get(item.id);
if (existing != null) {
// The engine's JS timeout and the AlarmManager alarm both fired: one ring.
showNotification(existing);
return;
}
if (takeEarlySignal(stoppedEarly, item.id)) {
// Acknowledged or cancelled before this intent was processed.
FaceclawAlarms.log(this, "ring " + item.id + " already acknowledged");
return;
}
ringing.put(item.id, item);
FaceclawAlarms.log(this, "ring " + item.kind + " " + item.id + " (" + FaceclawAlarms.glassesStatusDescription() + ")");
acquireWakeLock();
showNotification(item);
if (!FaceclawAlarms.glassesCanCarryAlarm()) {
escalate(item, FaceclawAlarms.glassesStatusDescription());
return;
}
if (takeEarlySignal(deliveredEarly, item.id)) {
markDelivered(item.id);
return;
}
// The glasses could carry it: give the JS side a moment to confirm
// they are actually showing it, then hold for the acknowledgement.
handler.postDelayed(() -> {
Ringing current = ringing.get(item.id);
if (current != null && !current.escalated && current.deliveredAtMs == 0) {
escalate(current, "not delivered to the glasses");
}
}, DELIVERY_WAIT_MS);
}
/** Consume an early signal for the id; stale entries are dropped. */
private static boolean takeEarlySignal(Map<Long, Long> signals, long id) {
Long at = signals.remove(id);
long now = System.currentTimeMillis();
synchronized (signals) {
signals.values().removeIf(stamp -> now - stamp > EARLY_SIGNAL_MAX_AGE_MS);
}
return at != null && now - at <= EARLY_SIGNAL_MAX_AGE_MS;
}
private void markDelivered(long id) {
Ringing item = ringing.get(id);
if (item == null || item.deliveredAtMs != 0) {
return;
}
item.deliveredAtMs = System.currentTimeMillis();
FaceclawAlarms.log(this, "delivered " + id + " to glasses");
handler.postDelayed(() -> {
Ringing current = ringing.get(id);
if (current != null && !current.escalated) {
escalate(current, "not acknowledged on the glasses");
}
}, ACK_WAIT_MS);
}
private void escalate(Ringing item, String reason) {
if (item.escalated) {
return;
}
item.escalated = true;
FaceclawAlarms.log(this, "phone sound for " + item.id + ": " + reason);
showNotification(item);
startSound();
handler.postDelayed(() -> {
Ringing current = ringing.get(item.id);
if (current != null && current.escalated && !current.silenced) {
current.silenced = true;
FaceclawAlarms.log(this, "auto-silenced " + current.id);
showNotification(current);
syncSound();
}
}, AUTO_SILENCE_MS);
}
private void dismiss(long id) {
Ringing item = ringing.get(id);
if (item == null) {
return;
}
FaceclawAlarms.recordPhoneAction(this, id, "dismiss", 0);
removeItem(item);
// Also drop the schedule entry (a one-off is over; the engine re-arms repeats).
FaceclawAlarms.cancel(this, id);
}
private void snooze(long id) {
Ringing item = ringing.get(id);
if (item == null) {
return;
}
int minutes = item.snoozeMinutes;
FaceclawAlarms.recordPhoneAction(this, id, "snooze", minutes);
removeItem(item);
// Re-arm on the phone directly so the snooze holds even with the JS
// side gone; the engine replays the journal and lands on the same id.
FaceclawAlarms.schedule(
this,
id,
System.currentTimeMillis() + minutes * 60_000L,
item.title,
item.text,
item.kind,
minutes
);
}
private void stopItemQuietly(long id, String reason) {
Ringing item = ringing.get(id);
if (item == null) {
return;
}
FaceclawAlarms.log(this, reason + " " + id);
removeItem(item);
}
private void removeItem(Ringing item) {
ringing.remove(item.id);
NotificationManager manager = getSystemService(NotificationManager.class);
if (manager != null) {
manager.cancel(notificationId(item.id));
}
syncSound();
if (item.id == foregroundId) {
promoteAnotherToForeground();
}
}
private void finishIfIdle() {
if (!ringing.isEmpty()) {
return;
}
handler.removeCallbacksAndMessages(null);
stopSound();
releaseWakeLock();
stopForeground(STOP_FOREGROUND_REMOVE);
stopSelf();
}
// ------------------------------------------------------------------
// Notification (the phone's silent display of the alarm)
private void showNotification(Ringing item) {
Notification notification = buildNotification(item);
if (foregroundId == 0 || foregroundId == item.id || !ringing.containsKey(foregroundId)) {
foregroundId = item.id;
startForegroundCompat(notificationId(item.id), notification);
} else {
NotificationManager manager = getSystemService(NotificationManager.class);
if (manager != null) {
manager.notify(notificationId(item.id), notification);
}
}
}
private void promoteAnotherToForeground() {
List<Ringing> items = snapshot();
if (items.isEmpty()) {
foregroundId = 0;
return;
}
Ringing next = items.get(0);
foregroundId = next.id;
startForegroundCompat(notificationId(next.id), buildNotification(next));
}
private void startForegroundCompat(int id, Notification notification) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
startForeground(id, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK);
} else {
startForeground(id, notification);
}
}
private Notification buildNotification(Ringing item) {
Intent activity = new Intent(this, FaceclawAlarmActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP)
.putExtra(FaceclawAlarms.EXTRA_ID, item.id);
int flags = PendingIntent.FLAG_UPDATE_CURRENT;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
flags |= PendingIntent.FLAG_IMMUTABLE;
}
PendingIntent open = PendingIntent.getActivity(this, FaceclawAlarms.requestCode(item.id), activity, flags);
String status;
if (item.silenced) {
status = "Not answered";
} else if (item.escalated) {
status = "Ringing";
} else {
status = "Ringing on the glasses";
}
String text = item.text.isEmpty() ? status : item.text + " · " + status;
Notification.Builder builder = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
? new Notification.Builder(this, CHANNEL_ID)
: new Notification.Builder(this).setPriority(Notification.PRIORITY_MAX);
builder.setContentTitle(item.title)
.setContentText(text)
.setSmallIcon(getApplicationInfo().icon)
.setContentIntent(open)
.setFullScreenIntent(open, true)
.setCategory(Notification.CATEGORY_ALARM)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setOngoing(true)
.setAutoCancel(false)
.setOnlyAlertOnce(true)
.setWhen(item.ringAtMs)
.setShowWhen(true)
.addAction(new Notification.Action.Builder(
null,
FaceclawAlarms.KIND_TIMER.equals(item.kind) ? "+" + item.snoozeMinutes + " min" : "Snooze " + item.snoozeMinutes + " min",
actionIntent(this, ACTION_SNOOZE, item.id)).build())
.addAction(new Notification.Action.Builder(
null,
"Dismiss",
actionIntent(this, ACTION_DISMISS, item.id)).build());
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
// Pre-channel: the builder controls sound, and we want none.
builder.setSound(null).setVibrate(null);
}
return builder.build();
}
private void ensureChannel() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
return;
}
NotificationManager manager = getSystemService(NotificationManager.class);
if (manager == null) {
return;
}
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "Alarms", NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("Timers and alarms going off. Silent here: the sound is played by the alarm itself.");
// The service plays the sound itself (on the alarm stream) so the
// notification stays silent and vibration-free on purpose.
channel.setSound(null, null);
channel.enableVibration(false);
channel.setBypassDnd(true);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
manager.createNotificationChannel(channel);
}
private static int notificationId(long id) {
return 0x41000000 | (FaceclawAlarms.requestCode(id) & 0x00ffffff);
}
// ------------------------------------------------------------------
// Sound and vibration (only while some item is escalated and not yet silenced)
private void syncSound() {
boolean wanted = false;
for (Ringing item : snapshot()) {
if (item.escalated && !item.silenced) {
wanted = true;
break;
}
}
if (wanted) {
startSound();
} else {
stopSound();
}
}
private void startSound() {
if (player != null) {
return;
}
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ALARM)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
raiseMutedAlarmVolume();
requestAudioFocus(attributes);
Uri tone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (tone == null) {
tone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
}
try {
MediaPlayer created = new MediaPlayer();
created.setAudioAttributes(attributes);
created.setDataSource(this, tone);
created.setLooping(true);
created.prepare();
created.start();
player = created;
} catch (Exception error) {
FaceclawAlarms.log(this, "alarm sound failed: " + error.getMessage());
player = null;
}
startVibration();
}
private void stopSound() {
if (player != null) {
try {
player.stop();
} catch (RuntimeException ignored) {
// Already stopped.
}
player.release();
player = null;
}
if (vibrator != null) {
vibrator.cancel();
vibrator = null;
}
abandonAudioFocus();
restoreAlarmVolume();
}
/**
* A muted alarm stream is the one thing that would keep an alarm clock
* silent; raise it for the duration of the ring and put it back after.
*/
private void raiseMutedAlarmVolume() {
if (audioManager == null) {
return;
}
try {
int current = audioManager.getStreamVolume(AudioManager.STREAM_ALARM);
int max = audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
if (current == 0 && max > 0) {
restoreAlarmVolume = current;
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, Math.max(1, Math.round(max * MUTED_VOLUME_FRACTION)), 0);
}
} catch (RuntimeException error) {
FaceclawAlarms.log(this, "alarm volume change failed: " + error.getMessage());
}
}
private void restoreAlarmVolume() {
if (audioManager == null || restoreAlarmVolume < 0) {
return;
}
try {
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, restoreAlarmVolume, 0);
} catch (RuntimeException ignored) {
// Best effort.
}
restoreAlarmVolume = -1;
}
private void requestAudioFocus(AudioAttributes attributes) {
if (audioManager == null) {
return;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
focusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT)
.setAudioAttributes(attributes)
.build();
audioManager.requestAudioFocus(focusRequest);
} else {
audioManager.requestAudioFocus(null, AudioManager.STREAM_ALARM, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
}
}
private void abandonAudioFocus() {
if (audioManager == null) {
return;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (focusRequest != null) {
audioManager.abandonAudioFocusRequest(focusRequest);
focusRequest = null;
}
} else {
audioManager.abandonAudioFocus(null);
}
}
private void startVibration() {
Vibrator device = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (device == null || !device.hasVibrator()) {
return;
}
vibrator = device;
long[] pattern = {0, 600, 400, 600, 1200};
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ALARM)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
device.vibrate(VibrationEffect.createWaveform(pattern, 0), attributes);
} else {
device.vibrate(pattern, 0, attributes);
}
} catch (RuntimeException error) {
FaceclawAlarms.log(this, "vibration failed: " + error.getMessage());
}
}
// ------------------------------------------------------------------
// Wake lock
private void acquireWakeLock() {
if (wakeLock != null && wakeLock.isHeld()) {
return;
}
PowerManager power = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (power == null) {
return;
}
wakeLock = power.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "faceclaw:alarm");
// Bounded: sound auto-silences at AUTO_SILENCE_MS, and a stuck lock
// past that would only drain the battery.
wakeLock.acquire(AUTO_SILENCE_MS + ACK_WAIT_MS + DELIVERY_WAIT_MS + 10_000L);
}
private void releaseWakeLock() {
if (wakeLock != null && wakeLock.isHeld()) {
wakeLock.release();
}
wakeLock = null;
}
}
@@ -0,0 +1,620 @@
package com.faceclaw.app;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.PowerManager;
import android.provider.Settings;
import androidx.core.content.ContextCompat;
import com.tns.NativeScriptActivity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Locale;
/**
* The phone side of the Timers app's alarms and countdown timers, built to
* ring without the JavaScript side: scheduling through AlarmManager's alarm
* clock API, a persisted schedule (in device-protected storage) that the
* reschedule receiver replays after reboots and time changes, the hand-off
* to the ringing foreground service, and a journal of what the wearer did
* on the phone (dismiss / snooze) for the JS engine to replay when it is
* next awake. Also the reliability self-check the UI surfaces.
*
* Ids are the JS engine's item ids (a millisecond epoch times 100 plus a
* serial), shared between timers and alarms; `kind` tells the two apart for
* wording only.
*/
public final class FaceclawAlarms {
public static final String ACTION_EXPIRE = "com.faceclaw.app.action.ALARM_EXPIRE";
static final String EXTRA_ID = "id";
static final String EXTRA_TITLE = "title";
static final String EXTRA_TEXT = "text";
static final String EXTRA_KIND = "kind";
static final String EXTRA_SNOOZE_MINUTES = "snoozeMinutes";
public static final String KIND_TIMER = "timer";
public static final String KIND_ALARM = "alarm";
private static final String PREFS_NAME = "faceclaw-alarms";
private static final String KEY_SCHEDULED = "scheduled";
private static final String KEY_JOURNAL = "journal";
private static final String KEY_LOG = "log";
private static final int LOG_LINES = 60;
/**
* A schedule entry found already past due (after a reboot, or when the
* process was asleep) rings if it is at most this late; older ones are
* dropped as missed. Matches the JS engine's grace window.
*/
static final long LATE_GRACE_MS = 5 * 60_000L;
/** A glasses status report older than this is not trusted (the JS side is probably gone). */
static final long GLASSES_STATUS_MAX_AGE_MS = 3 * 60_000L;
private static volatile boolean glassesConnected;
private static volatile boolean glassesWorn;
private static volatile boolean glassesCharging;
private static volatile long glassesStatusAtMs;
private static volatile FaceclawAlarmListener listener;
private static final Handler mainHandler = new Handler(Looper.getMainLooper());
private FaceclawAlarms() {}
// ------------------------------------------------------------------
// Storage
/**
* Device-protected storage, so the schedule is readable before the first
* unlock after a reboot (the reschedule receiver may run then on some
* devices) and survives credential-encrypted storage being unavailable.
*/
static SharedPreferences prefs(Context context) {
Context base = context.getApplicationContext();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
base = base.createDeviceProtectedStorageContext();
}
return base.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
}
private static synchronized JSONArray readArray(Context context, String key) {
String raw = prefs(context).getString(key, "[]");
try {
return new JSONArray(raw);
} catch (JSONException error) {
return new JSONArray();
}
}
private static synchronized void writeArray(Context context, String key, JSONArray array) {
prefs(context).edit().putString(key, array.toString()).apply();
}
static JSONObject findScheduled(Context context, long id) {
JSONArray scheduled = readArray(context, KEY_SCHEDULED);
for (int index = 0; index < scheduled.length(); index++) {
JSONObject entry = scheduled.optJSONObject(index);
if (entry != null && entry.optLong("id") == id) {
return entry;
}
}
return null;
}
private static synchronized void putScheduled(Context context, JSONObject entry) {
JSONArray scheduled = readArray(context, KEY_SCHEDULED);
JSONArray next = new JSONArray();
long id = entry.optLong("id");
for (int index = 0; index < scheduled.length(); index++) {
JSONObject existing = scheduled.optJSONObject(index);
if (existing != null && existing.optLong("id") != id) {
next.put(existing);
}
}
next.put(entry);
writeArray(context, KEY_SCHEDULED, next);
}
private static synchronized void removeScheduled(Context context, long id) {
JSONArray scheduled = readArray(context, KEY_SCHEDULED);
JSONArray next = new JSONArray();
for (int index = 0; index < scheduled.length(); index++) {
JSONObject existing = scheduled.optJSONObject(index);
if (existing != null && existing.optLong("id") != id) {
next.put(existing);
}
}
writeArray(context, KEY_SCHEDULED, next);
}
// ------------------------------------------------------------------
// Scheduling
/**
* Schedule (or move) the phone alarm for an item. Idempotent: the same id
* always maps to the same PendingIntent, so a reschedule replaces rather
* than duplicates. setAlarmClock is exact, fires through Doze and battery
* savers, and shows the system's alarm indicator; the fallbacks only run
* where it is unavailable.
*/
public static void schedule(
Context context,
long id,
long triggerAtMs,
String title,
String text,
String kind,
int snoozeMinutes
) {
Context appContext = context.getApplicationContext();
JSONObject entry = new JSONObject();
try {
entry.put("id", id);
entry.put("at", triggerAtMs);
entry.put("title", title == null ? "" : title);
entry.put("text", text == null ? "" : text);
entry.put("kind", kind == null ? KIND_ALARM : kind);
entry.put("snoozeMinutes", snoozeMinutes);
} catch (JSONException ignored) {
return;
}
putScheduled(appContext, entry);
armAlarm(appContext, entry);
}
private static void armAlarm(Context appContext, JSONObject entry) {
AlarmManager manager = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
if (manager == null) {
return;
}
long id = entry.optLong("id");
long triggerAt = Math.max(System.currentTimeMillis(), entry.optLong("at"));
PendingIntent fire = expiryPendingIntent(appContext, entry);
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
AlarmManager.AlarmClockInfo info = new AlarmManager.AlarmClockInfo(triggerAt, showIntent(appContext, id));
manager.setAlarmClock(info, fire);
} else {
manager.setExact(AlarmManager.RTC_WAKEUP, triggerAt, fire);
}
} catch (SecurityException error) {
// Exact-alarm access revoked (Android 12/13 without USE_EXACT_ALARM
// honoured): the inexact alarm is still a wake-up, just a late one.
log(appContext, "exact alarm refused for " + id + ": " + error.getMessage());
manager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAt, fire);
}
}
/** Cancel the phone alarm for an item, stop it if ringing, and forget it. */
public static void cancel(Context context, long id) {
Context appContext = context.getApplicationContext();
AlarmManager manager = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
if (manager != null) {
JSONObject entry = new JSONObject();
try {
entry.put("id", id);
} catch (JSONException ignored) {
// unreachable for a numeric put
}
manager.cancel(expiryPendingIntent(appContext, entry));
}
removeScheduled(appContext, id);
FaceclawAlarmService.stopItem(appContext, id);
}
/**
* Replay the persisted schedule into AlarmManager: after a reboot (alarms
* are wiped), a package update, or a wall-clock / time-zone change. Entries
* already due ring now if inside the grace window, else are dropped.
*/
public static void rescheduleAll(Context context, String reason) {
Context appContext = context.getApplicationContext();
JSONArray scheduled = readArray(appContext, KEY_SCHEDULED);
long now = System.currentTimeMillis();
int armed = 0;
for (int index = 0; index < scheduled.length(); index++) {
JSONObject entry = scheduled.optJSONObject(index);
if (entry == null) {
continue;
}
long at = entry.optLong("at");
if (at <= now) {
if (now - at <= LATE_GRACE_MS) {
ringEntry(appContext, entry);
} else {
log(appContext, "missed " + entry.optString("kind") + " " + entry.optLong("id") + " (" + reason + ")");
removeScheduled(appContext, entry.optLong("id"));
}
continue;
}
armAlarm(appContext, entry);
armed++;
}
log(appContext, "rescheduled " + armed + " (" + reason + ")");
}
/**
* The schedule and AlarmManager can disagree (a force-stop clears alarms
* but not the file, an OEM killer drops them). True when the soonest
* stored entry is not what the system reports as the next alarm clock.
*/
public static boolean scheduleLooksStale(Context context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
return false;
}
Context appContext = context.getApplicationContext();
JSONArray scheduled = readArray(appContext, KEY_SCHEDULED);
long now = System.currentTimeMillis();
long soonest = Long.MAX_VALUE;
for (int index = 0; index < scheduled.length(); index++) {
JSONObject entry = scheduled.optJSONObject(index);
if (entry != null && entry.optLong("at") > now) {
soonest = Math.min(soonest, entry.optLong("at"));
}
}
if (soonest == Long.MAX_VALUE) {
return false;
}
AlarmManager manager = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
if (manager == null) {
return false;
}
AlarmManager.AlarmClockInfo next = manager.getNextAlarmClock();
// Another app's alarm may legitimately be sooner; only a later (or
// absent) system alarm proves ours is missing.
return next == null || next.getTriggerTime() > soonest + 1000;
}
// ------------------------------------------------------------------
// Ringing
/** An item came due: hand it to the ringing service (idempotent per id). */
static void ringEntry(Context appContext, JSONObject entry) {
FaceclawAlarmService.ring(
appContext,
entry.optLong("id"),
entry.optString("title"),
entry.optString("text"),
entry.optString("kind", KIND_ALARM),
entry.optInt("snoozeMinutes", 10)
);
}
/** The JS engine's own expiry path; the service deduplicates against the alarm's. */
public static void ring(Context context, long id, String title, String text, String kind, int snoozeMinutes) {
Context appContext = context.getApplicationContext();
AlarmManager manager = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
if (manager != null) {
JSONObject probe = new JSONObject();
try {
probe.put("id", id);
} catch (JSONException ignored) {
// unreachable for a numeric put
}
manager.cancel(expiryPendingIntent(appContext, probe));
}
FaceclawAlarmService.ring(appContext, id, title, text, kind, snoozeMinutes);
}
/** The glasses are showing the ringing item; the acknowledgement clock starts now. */
public static void deliveredToGlasses(Context context, long id) {
FaceclawAlarmService.delivered(context.getApplicationContext(), id);
}
/** The wearer dismissed or snoozed it on the glasses: the phone side goes quiet. */
public static void acknowledge(Context context, long id) {
Context appContext = context.getApplicationContext();
removeScheduled(appContext, id);
FaceclawAlarmService.stopItem(appContext, id);
}
// ------------------------------------------------------------------
// Glasses status (pushed by the JS side; in-memory, so a dead process reads as "no glasses")
public static void setGlassesStatus(boolean connected, boolean worn, boolean charging) {
glassesConnected = connected;
glassesWorn = worn;
glassesCharging = charging;
glassesStatusAtMs = System.currentTimeMillis();
}
/** True only when a fresh report says the glasses are connected, on a head, and not charging. */
static boolean glassesCanCarryAlarm() {
long age = System.currentTimeMillis() - glassesStatusAtMs;
if (glassesStatusAtMs == 0 || age > GLASSES_STATUS_MAX_AGE_MS) {
return false;
}
return glassesConnected && glassesWorn && !glassesCharging;
}
static String glassesStatusDescription() {
if (glassesStatusAtMs == 0) {
return "no glasses status";
}
long age = System.currentTimeMillis() - glassesStatusAtMs;
if (age > GLASSES_STATUS_MAX_AGE_MS) {
return "glasses status stale";
}
if (!glassesConnected) {
return "glasses not connected";
}
if (glassesCharging) {
return "glasses charging";
}
if (!glassesWorn) {
return "glasses not worn";
}
return "glasses worn";
}
// ------------------------------------------------------------------
// Phone actions -> JS
public static void setListener(FaceclawAlarmListener newListener) {
listener = newListener;
}
/**
* Record a dismiss / snooze done on the phone. Delivered live to the JS
* listener when one is registered, and journaled regardless so a JS side
* that was asleep or gone can catch up on its next boot.
*/
static void recordPhoneAction(Context context, long id, String action, int minutes) {
Context appContext = context.getApplicationContext();
JSONObject event = new JSONObject();
try {
event.put("id", id);
event.put("action", action);
event.put("minutes", minutes);
event.put("at", System.currentTimeMillis());
} catch (JSONException ignored) {
return;
}
synchronized (FaceclawAlarms.class) {
JSONArray journal = readArray(appContext, KEY_JOURNAL);
journal.put(event);
writeArray(appContext, KEY_JOURNAL, journal);
}
log(appContext, "phone " + action + " " + id + (minutes > 0 ? " (" + minutes + " min)" : ""));
final FaceclawAlarmListener current = listener;
if (current != null) {
mainHandler.post(() -> {
try {
current.onPhoneAction(id, action, minutes);
} catch (RuntimeException error) {
log(appContext, "listener failed: " + error.getMessage());
}
});
}
}
/** Hand the journal to the JS side (as a JSON array) and clear it. */
public static synchronized String drainJournal(Context context) {
Context appContext = context.getApplicationContext();
JSONArray journal = readArray(appContext, KEY_JOURNAL);
writeArray(appContext, KEY_JOURNAL, new JSONArray());
return journal.toString();
}
// ------------------------------------------------------------------
// Reliability self-check
/**
* Conditions under which the phone may fail to ring, as a JSON array of
* {code, message, fixable}, most serious first. Empty when everything is
* in order. The UI shows these before the wearer relies on an alarm.
*/
public static String checkReliability(Context context) {
Context appContext = context.getApplicationContext();
JSONArray issues = new JSONArray();
NotificationManager notifications = (NotificationManager) appContext.getSystemService(Context.NOTIFICATION_SERVICE);
AlarmManager alarms = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && alarms != null && !alarms.canScheduleExactAlarms()) {
addIssue(issues, "exact-alarm", "Exact alarms are not allowed for Faceclaw, so alarms may ring late.", true);
}
if (notifications != null && !notifications.areNotificationsEnabled()) {
addIssue(issues, "notifications", "Notifications are turned off for Faceclaw, so the phone cannot show or sound an alarm.", true);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && notifications != null) {
NotificationChannel channel = notifications.getNotificationChannel(FaceclawAlarmService.CHANNEL_ID);
if (channel != null && channel.getImportance() == NotificationManager.IMPORTANCE_NONE) {
addIssue(issues, "alarm-channel", "The Alarms notification category is blocked, so the phone cannot show an alarm.", true);
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE && notifications != null && !notifications.canUseFullScreenIntent()) {
addIssue(issues, "full-screen", "Full-screen alarms are not allowed, so a ringing alarm will not take over the lock screen.", true);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && notifications != null) {
int filter = notifications.getCurrentInterruptionFilter();
if (filter == NotificationManager.INTERRUPTION_FILTER_NONE) {
addIssue(issues, "dnd-total", "Do Not Disturb is set to total silence, which silences alarms too.", true);
} else if (filter == NotificationManager.INTERRUPTION_FILTER_PRIORITY) {
try {
NotificationManager.Policy policy = notifications.getNotificationPolicy();
if (policy != null && (policy.priorityCategories & NotificationManager.Policy.PRIORITY_CATEGORY_ALARMS) == 0) {
addIssue(issues, "dnd-alarms", "Do Not Disturb does not allow alarms, so the phone will stay silent.", true);
}
} catch (SecurityException ignored) {
// No notification-policy access: cannot inspect the exceptions.
}
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
ActivityManager activityManager = (ActivityManager) appContext.getSystemService(Context.ACTIVITY_SERVICE);
if (activityManager != null && activityManager.isBackgroundRestricted()) {
addIssue(issues, "background-restricted", "Background usage is restricted for Faceclaw, which blocks alarms while the app is not open.", true);
}
}
PowerManager power = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
if (power != null && !power.isIgnoringBatteryOptimizations(appContext.getPackageName())) {
addIssue(issues, "battery-optimized", "Battery optimization is on for Faceclaw; some phones delay alarms because of it.", true);
}
AudioManager audio = (AudioManager) appContext.getSystemService(Context.AUDIO_SERVICE);
if (audio != null && audio.getStreamVolume(AudioManager.STREAM_ALARM) == 0) {
addIssue(issues, "alarm-volume", "The phone's alarm volume is muted; Faceclaw raises it while ringing, but check it.", true);
}
String maker = Build.MANUFACTURER == null ? "" : Build.MANUFACTURER.toLowerCase(Locale.ROOT);
if (maker.contains("xiaomi") || maker.contains("huawei") || maker.contains("oppo") || maker.contains("vivo")
|| maker.contains("oneplus") || maker.contains("realme") || maker.contains("meizu") || maker.contains("asus")) {
addIssue(issues, "oem-killer", "This phone maker is known to stop background apps; allow Faceclaw to auto-start and run unrestricted (see dontkillmyapp.com).", true);
}
if (scheduleLooksStale(appContext)) {
addIssue(issues, "schedule-stale", "The system lost Faceclaw's next alarm (the app may have been force-stopped); it was re-armed.", false);
rescheduleAll(appContext, "self-check");
}
return issues.toString();
}
private static void addIssue(JSONArray issues, String code, String message, boolean fixable) {
JSONObject issue = new JSONObject();
try {
issue.put("code", code);
issue.put("message", message);
issue.put("fixable", fixable);
} catch (JSONException ignored) {
return;
}
issues.put(issue);
}
/** Open the system screen where the issue can be fixed. */
public static void openReliabilityFix(Context context, String code) {
Context appContext = context.getApplicationContext();
String pkg = appContext.getPackageName();
Intent intent;
switch (code == null ? "" : code) {
case "exact-alarm":
intent = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
? new Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM, Uri.parse("package:" + pkg))
: appDetails(pkg);
break;
case "notifications":
case "alarm-channel":
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
intent = new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
.putExtra(Settings.EXTRA_APP_PACKAGE, pkg);
if ("alarm-channel".equals(code)) {
intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS)
.putExtra(Settings.EXTRA_APP_PACKAGE, pkg)
.putExtra(Settings.EXTRA_CHANNEL_ID, FaceclawAlarmService.CHANNEL_ID);
}
} else {
intent = appDetails(pkg);
}
break;
case "full-screen":
intent = Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE
? new Intent(Settings.ACTION_MANAGE_APP_USE_FULL_SCREEN_INTENT, Uri.parse("package:" + pkg))
: appDetails(pkg);
break;
case "dnd-total":
case "dnd-alarms":
intent = new Intent(Settings.ACTION_SOUND_SETTINGS);
break;
case "battery-optimized":
intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, Uri.parse("package:" + pkg));
break;
case "alarm-volume":
intent = new Intent(Settings.ACTION_SOUND_SETTINGS);
break;
default:
intent = appDetails(pkg);
break;
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
appContext.startActivity(intent);
} catch (RuntimeException error) {
Intent fallback = appDetails(pkg).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
appContext.startActivity(fallback);
} catch (RuntimeException ignored) {
// No settings activity at all; nothing more to do.
}
}
}
private static Intent appDetails(String pkg) {
return new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + pkg));
}
// ------------------------------------------------------------------
// Diagnostics log
static synchronized void log(Context context, String line) {
Context appContext = context.getApplicationContext();
JSONArray log = readArray(appContext, KEY_LOG);
JSONArray next = new JSONArray();
int start = Math.max(0, log.length() - (LOG_LINES - 1));
for (int index = start; index < log.length(); index++) {
next.put(log.optString(index));
}
next.put(System.currentTimeMillis() + " " + line);
writeArray(appContext, KEY_LOG, next);
}
/** The ring / miss / action log, newest last, one line per entry. */
public static String readLog(Context context) {
JSONArray log = readArray(context.getApplicationContext(), KEY_LOG);
StringBuilder out = new StringBuilder();
for (int index = 0; index < log.length(); index++) {
if (index > 0) {
out.append('\n');
}
out.append(log.optString(index));
}
return out.toString();
}
// ------------------------------------------------------------------
// Intents
private static PendingIntent expiryPendingIntent(Context appContext, JSONObject entry) {
Intent intent = new Intent(appContext, FaceclawAlarmReceiver.class);
intent.setAction(ACTION_EXPIRE);
long id = entry.optLong("id");
intent.putExtra(EXTRA_ID, id);
intent.putExtra(EXTRA_TITLE, entry.optString("title"));
intent.putExtra(EXTRA_TEXT, entry.optString("text"));
intent.putExtra(EXTRA_KIND, entry.optString("kind", KIND_ALARM));
intent.putExtra(EXTRA_SNOOZE_MINUTES, entry.optInt("snoozeMinutes", 10));
int flags = PendingIntent.FLAG_UPDATE_CURRENT;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
flags |= PendingIntent.FLAG_IMMUTABLE;
}
return PendingIntent.getBroadcast(appContext, requestCode(id), intent, flags);
}
/** What the system's alarm indicator opens: the app. */
private static PendingIntent showIntent(Context appContext, long id) {
Intent intent = new Intent(appContext, NativeScriptActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
int flags = PendingIntent.FLAG_UPDATE_CURRENT;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
flags |= PendingIntent.FLAG_IMMUTABLE;
}
return PendingIntent.getActivity(appContext, requestCode(id), intent, flags);
}
static int requestCode(long id) {
return (int) (id ^ (id >>> 32)) & 0x7fffffff;
}
static void startServiceCompat(Context appContext, Intent intent) {
ContextCompat.startForegroundService(appContext, intent);
}
}
@@ -1,196 +0,0 @@
package com.faceclaw.app;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import com.tns.NativeScriptActivity;
/**
* Android alarm + notification bridge used by the on-glasses Timers app, for
* countdown timers and alarms alike: one AlarmManager alarm per item posts a
* phone notification at the moment of expiry, even when the app process is
* asleep or gone.
*/
public final class FaceclawTimerNotifications {
public static final String CHANNEL_ID = "faceclaw-timers";
static final String ACTION_EXPIRE = "com.faceclaw.app.action.TIMER_EXPIRE";
static final String EXTRA_TIMER_ID = "timerId";
static final String EXTRA_TITLE = "title";
static final String EXTRA_TEXT = "text";
private static final String TIMER_TAG_PREFIX = "faceclaw-timer:";
private static final String PREFS_NAME = "faceclaw-timer-notifications";
private static final String FIRED_KEY_PREFIX = "fired:";
private FaceclawTimerNotifications() {}
/**
* Schedule an Android alarm as the durable path. The engine also keeps a
* normal JS timeout for prompt delivery while the process is awake.
*/
public static void schedule(Context context, long timerId, long triggerAtMs, String title, String text) {
Context appContext = context.getApplicationContext();
preferences(appContext).edit().putBoolean(firedKey(timerId), false).apply();
AlarmManager manager = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
if (manager == null) {
return;
}
PendingIntent pendingIntent = expiryPendingIntent(appContext, timerId, title, text);
long triggerAt = Math.max(System.currentTimeMillis(), triggerAtMs);
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && !manager.canScheduleExactAlarms()) {
manager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAt, pendingIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAt, pendingIntent);
} else {
manager.setExact(AlarmManager.RTC_WAKEUP, triggerAt, pendingIntent);
}
} catch (SecurityException ignored) {
// Exact-alarm access can be disabled by the user on recent Android.
// The inexact alarm remains a durable backup to the worker timeout.
manager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAt, pendingIntent);
}
}
public static void cancel(Context context, long timerId) {
Context appContext = context.getApplicationContext();
AlarmManager alarmManager = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
if (alarmManager != null) {
alarmManager.cancel(expiryPendingIntent(appContext, timerId, "", ""));
}
NotificationManager notificationManager =
(NotificationManager) appContext.getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.cancel(notificationTag(timerId), notificationId(timerId));
}
preferences(appContext).edit().remove(firedKey(timerId)).apply();
}
/** Engine-timeout path. Cancels the backup alarm and posts at most once. */
public static void fireNow(Context context, long timerId, String title, String text) {
Context appContext = context.getApplicationContext();
AlarmManager alarmManager = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
if (alarmManager != null) {
alarmManager.cancel(expiryPendingIntent(appContext, timerId, title, text));
}
showExpiredOnce(appContext, timerId, title, text);
}
static synchronized void showExpiredOnce(Context context, long timerId, String title, String text) {
SharedPreferences preferences = preferences(context);
String firedKey = firedKey(timerId);
if (preferences.getBoolean(firedKey, false)) {
return;
}
preferences.edit().putBoolean(firedKey, true).apply();
ensureChannel(context);
Intent launchIntent = new Intent(context, NativeScriptActivity.class);
launchIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
int contentFlags = PendingIntent.FLAG_UPDATE_CURRENT;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
contentFlags |= PendingIntent.FLAG_IMMUTABLE;
}
PendingIntent contentIntent = PendingIntent.getActivity(
context,
notificationId(timerId),
launchIntent,
contentFlags
);
Notification.Builder builder = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
? new Notification.Builder(context, CHANNEL_ID)
: new Notification.Builder(context);
String contentTitle = title == null || title.trim().isEmpty() ? "Timer finished" : title;
String contentText = text == null || text.trim().isEmpty() ? "Time's up" : text;
Notification notification = builder
.setContentTitle(contentTitle)
.setContentText(contentText)
.setSmallIcon(context.getApplicationInfo().icon)
.setContentIntent(contentIntent)
.setCategory(Notification.CATEGORY_ALARM)
.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.setShowWhen(true)
.build();
NotificationManager manager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (manager != null) {
manager.notify(notificationTag(timerId), notificationId(timerId), notification);
}
}
/** Identifies this bridge's notifications among our own package's (see the listener service). */
public static boolean isTimerNotification(android.service.notification.StatusBarNotification item) {
if (item == null || item.getNotification() == null) {
return false;
}
String tag = item.getTag();
if (tag != null && tag.startsWith(TIMER_TAG_PREFIX)) {
return true;
}
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
&& CHANNEL_ID.equals(item.getNotification().getChannelId());
}
private static void ensureChannel(Context context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
return;
}
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"Timers",
NotificationManager.IMPORTANCE_HIGH
);
channel.setDescription("Alerts when a Faceclaw timer finishes.");
channel.enableVibration(true);
NotificationManager manager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (manager != null) {
manager.createNotificationChannel(channel);
}
}
private static PendingIntent expiryPendingIntent(
Context context,
long timerId,
String title,
String text
) {
Intent intent = new Intent(context, FaceclawTimerReceiver.class);
intent.setAction(ACTION_EXPIRE);
intent.putExtra(EXTRA_TIMER_ID, timerId);
intent.putExtra(EXTRA_TITLE, title == null ? "" : title);
intent.putExtra(EXTRA_TEXT, text == null ? "" : text);
int flags = PendingIntent.FLAG_UPDATE_CURRENT;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
flags |= PendingIntent.FLAG_IMMUTABLE;
}
return PendingIntent.getBroadcast(context, notificationId(timerId), intent, flags);
}
private static SharedPreferences preferences(Context context) {
return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
}
private static String firedKey(long timerId) {
return FIRED_KEY_PREFIX + timerId;
}
private static String notificationTag(long timerId) {
return TIMER_TAG_PREFIX + timerId;
}
private static int notificationId(long timerId) {
return (int) (timerId ^ (timerId >>> 32)) & 0x7fffffff;
}
}
@@ -1,22 +0,0 @@
package com.faceclaw.app;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/** Receives durable timer/alarm expiries even if the NativeScript side is asleep. */
public class FaceclawTimerReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent == null || !FaceclawTimerNotifications.ACTION_EXPIRE.equals(intent.getAction())) {
return;
}
long timerId = intent.getLongExtra(FaceclawTimerNotifications.EXTRA_TIMER_ID, 0);
if (timerId == 0) {
return;
}
String title = intent.getStringExtra(FaceclawTimerNotifications.EXTRA_TITLE);
String text = intent.getStringExtra(FaceclawTimerNotifications.EXTRA_TEXT);
FaceclawTimerNotifications.showExpiredOnce(context, timerId, title, text);
}
}
+7 -2
View File
@@ -16,14 +16,19 @@ const timerApp: AppDefinition = {
boot: (ctx) => {
timerEngine.boot({
playBuzzer: (payload) => ctx.actions.playBuzzerSequence(payload),
onRing: () => {
onRing: (item) => {
// Bring the ringing item on screen: focus the Timers window, then
// wake the display if it is off (a setting, since a wearer may
// prefer the phone notification alone while the glasses sleep).
// prefer the phone alone while the glasses sleep). Only once it is
// actually showing does the phone start its acknowledgement clock;
// otherwise the phone adds its own sound within seconds.
void ctx
.launchApp("timer")
.then(() => {
if (timersWakeSetting.get() && !shell.isScreenOn()) shell.wake("window");
if (shell.isScreenOn() && shell.foregroundWindow()?.windowId === TIMER_WINDOW_ID) {
timerEngine.markDeliveredToGlasses(item);
}
})
.catch((error) => console.error(`timers ring launch failed: ${error}`));
},
+16
View File
@@ -36,6 +36,7 @@ import {
drawSelectionHighlight,
drawToggleMenuItem,
scrollToKeepSelectionVisible,
TextPageLayer,
type MenuItem,
} from "../../ui/menu";
import { LIST_ROW_TEXT_INSET, lineStep, listRowHeight } from "../../ui/metrics";
@@ -820,6 +821,19 @@ export class TimersLayer implements Layer {
drawRightValueMenuItem(args.image, smallFont(), args.x, args.y, args.width, args.text, timersSnoozeSetting.displayValue()),
},
toggle("12-hour clock", () => twelveHour(), (value) => timeFormatSetting.set(value ? "12h" : "24h")),
{
label: "Phone alarm check",
onSelect: (ctx) => {
timerEngine.refreshReliability(true);
const issues = timerEngine.phoneReliabilityIssues();
const body =
issues.length === 0
? "No problems found: the phone can ring for alarms when the glasses cannot."
: issues.map((issue) => `- ${issue.message}`).join("\n") +
"\n\nFix these from the warning triangle on the phone's home screen.";
ctx.stack.push(new TextPageLayer("Phone alarm check", body));
},
},
];
}
@@ -1047,6 +1061,8 @@ export class TimersLayer implements Layer {
status = next === null ? "Off" : `Rings in ${formatSpanWords(next - now)}`;
}
block.line(image, status, 150);
const warning = timerEngine.phoneReliabilityIssues()[0];
if (alarm.enabled && warning) block.line(image, `Phone: ${warning.message}`, 120);
block.hints(image, [[GESTURE_CLICK, alarm.enabled ? "turn off" : "turn on"], [GESTURE_SHORT_THEN_LONG_PRESS, "edit"]]);
}
+158 -23
View File
@@ -1,26 +1,39 @@
/**
* The Timers app's clock engine: a main-thread singleton that owns the
* timers / stopwatch / alarms state, persists it, schedules the durable
* Android alarms behind every expiry, rings the glasses buzzer, and tells
* phone alarms behind every expiry, rings the glasses buzzer, and tells
* listeners (the window, the tray icon, the assistant tools) when anything
* changes. It is booted at shell start, so everything here works with the
* window closed; the window is only a view on it.
*
* Two expiry paths run side by side, as before: a JS deadline for prompt
* on-glasses ringing while the process is awake, and an AlarmManager alarm
* (see FaceclawTimerNotifications.java) that posts the phone notification
* at the right moment even if the process is asleep or dead. The Java side
* deduplicates the two.
* Two expiry paths run side by side: a JS deadline for prompt on-glasses
* ringing while the process is awake, and an AlarmManager alarm-clock alarm
* (FaceclawAlarms.java) that rings on the phone at the right moment even if
* the process is asleep or dead. The phone shows the item silently first
* and adds its own sound when the glasses cannot carry it (not connected,
* not worn, charging, not shown within seconds, or not acknowledged within
* 30 s); this engine keeps the phone told about the glasses, reports
* delivery and acknowledgement, and replays what the wearer did on the
* phone (dismiss / snooze) into its own state.
*/
import { ConfigSettingBoolean, ConfigSettingEnum } from "../../ui/dashboard-settings";
import { ConfigSettingBoolean, ConfigSettingEnum, timeFormatSetting } from "../../ui/dashboard-settings";
import { getStringSetting, setStringSetting } from "../../native/settings-store";
import {
cancelTimerNotification,
fireTimerNotification,
scheduleTimerNotification,
} from "../../native/timer-notifications";
acknowledgePhoneAlarm,
cancelPhoneAlarm,
checkPhoneAlarmReliability,
drainPhoneAlarmJournal,
onPhoneAlarmAction,
openPhoneAlarmReliabilityFix,
phoneAlarmDeliveredToGlasses,
ringPhoneAlarm,
schedulePhoneAlarm,
setPhoneAlarmGlassesStatus,
type AlarmReliabilityIssue,
type PhoneAlarmAction,
} from "../../native/alarms";
import { getGlassesPresence, glassesCanCarryAlert, onGlassesPresenceChanged } from "../../g2/glasses-presence";
import { buildSoundSequencePayload, findSoundEffect, effectPhrases } from "../../ui/sound-effects";
import { timeFormatSetting } from "../../ui/dashboard-settings";
import {
alarmNextRingMs,
createAlarm,
@@ -55,6 +68,10 @@ const RING_MAX_MS = 2 * 60_000;
* delayed by Doze or a clock jump can't leave a due item unnoticed for long.
*/
const MAX_ARM_MS = 30_000;
/** How often the phone is reminded of the glasses' status (it distrusts stale reports). */
const GLASSES_STATUS_HEARTBEAT_MS = 60_000;
/** How often the phone-side reliability self-check reruns while something is armed. */
const RELIABILITY_CHECK_MS = 5 * 60_000;
export const timersSoundSetting = new ConfigSettingBoolean({
id: "timersSound",
@@ -100,6 +117,8 @@ export class TimerEngine {
private deadlineTimer: ReturnType<typeof setTimeout> | null = null;
private ringTimer: ReturnType<typeof setInterval> | null = null;
private booted = false;
private reliabilityIssues: AlarmReliabilityIssue[] = [];
private reliabilityCheckedAtMs = 0;
constructor(private readonly now: () => number = () => Date.now()) {
this.state = emptyTimersState();
@@ -118,12 +137,117 @@ export class TimerEngine {
// Loaded here rather than at module evaluation, so the settings store is
// certainly up before the first read.
this.state = parseTimersState(getStringSetting(STATE_KEY, ""));
// What the wearer did on the phone while this side was down comes first,
// so a dismissed alarm is not rung again by the check below.
for (const action of drainPhoneAlarmJournal()) this.applyPhoneAction(action);
onPhoneAlarmAction((action) => {
this.applyPhoneAction(action);
this.commit();
});
this.pushGlassesStatus();
onGlassesPresenceChanged(() => this.pushGlassesStatus());
setInterval(() => this.pushGlassesStatus(), GLASSES_STATUS_HEARTBEAT_MS);
this.check();
for (const timer of this.state.timers) {
if (timer.endsAtMs !== null && timer.rungAtMs === null) this.schedulePhoneNotification(timer);
}
for (const alarm of this.state.alarms) this.schedulePhoneAlarm(alarm);
this.save();
this.refreshReliability(true);
setInterval(() => this.refreshReliability(false), RELIABILITY_CHECK_MS);
}
/**
* The glasses are showing a ringing item (the window is up and the screen
* on). The phone's 30-second acknowledgement clock starts from here; without
* this, the phone adds its sound within seconds.
*/
markDeliveredToGlasses(item: RingingItem): void {
if (!glassesCanCarryAlert()) return;
phoneAlarmDeliveredToGlasses(item.kind === "timer" ? item.timer.id : item.alarm.id);
}
private pushGlassesStatus(): void {
const presence = getGlassesPresence();
setPhoneAlarmGlassesStatus(presence.connected, presence.worn === true, presence.charging);
}
/**
* Replay a phone-side dismiss or snooze. The item may be ringing here too,
* may not have been noticed yet (the phone rang it while this side slept),
* or may already be gone; each case lands on the same end state.
*/
private applyPhoneAction(action: PhoneAlarmAction): void {
const at = action.atMs || this.now();
const timer = this.findTimer(action.id);
if (timer) {
if (action.action === "dismiss") {
this.state.timers = this.state.timers.filter((candidate) => candidate.id !== timer.id);
} else {
const extra = Math.max(1, action.minutes) * 60_000;
timer.rungAtMs = null;
timer.pausedRemainingMs = null;
timer.durationMs = extra;
timer.endsAtMs = at + extra;
}
return;
}
const alarm = this.findAlarm(action.id);
if (!alarm) return;
alarm.ringingSinceMs = null;
alarm.lastFiredAtMs = Math.max(alarm.lastFiredAtMs ?? 0, at);
if (action.action === "dismiss") {
alarm.snoozedUntilMs = null;
if (alarm.days === 0) alarm.enabled = false;
} else {
alarm.snoozedUntilMs = at + Math.max(1, action.minutes) * 60_000;
}
}
// -------------------------------------------------------------------------
// Phone reliability
/** Conditions under which the phone may fail to ring, most serious first (cached). */
phoneReliabilityIssues(): AlarmReliabilityIssue[] {
return this.reliabilityIssues;
}
/**
* One-line warning for the UI, or "" when nothing is armed that could
* suffer (no enabled alarm, no running timer) or nothing is wrong.
*/
phoneReliabilityMessage(): string {
if (this.reliabilityIssues.length === 0) return "";
const armed =
this.state.alarms.some((alarm) => alarm.enabled) ||
this.state.timers.some((timer) => timer.endsAtMs !== null && timer.rungAtMs === null);
if (!armed) return "";
return `The phone may not ring for alarms: ${this.reliabilityIssues[0]!.message}`;
}
/** Open the system screen for the most serious fixable issue, if any. */
openPhoneReliabilityFix(): void {
const issue = this.reliabilityIssues.find((candidate) => candidate.fixable);
if (issue) openPhoneAlarmReliabilityFix(issue.code);
}
/** Re-run the phone self-check (rate-limited unless forced) and notify on change. */
refreshReliability(force: boolean): void {
const now = this.now();
if (!force && now - this.reliabilityCheckedAtMs < 30_000) return;
this.reliabilityCheckedAtMs = now;
let issues: AlarmReliabilityIssue[];
try {
issues = checkPhoneAlarmReliability();
} catch (error) {
console.warn(`alarm reliability check failed: ${error}`);
return;
}
const changed =
issues.length !== this.reliabilityIssues.length ||
issues.some((issue, index) => issue.code !== this.reliabilityIssues[index]?.code);
this.reliabilityIssues = issues;
if (changed) this.notify();
}
onChange(listener: () => void): () => void {
@@ -174,7 +298,7 @@ export class TimerEngine {
if (!timer || timer.endsAtMs === null || timer.rungAtMs !== null) return;
timer.pausedRemainingMs = Math.max(0, timer.endsAtMs - this.now());
timer.endsAtMs = null;
cancelTimerNotification(timer.id);
cancelPhoneAlarm(timer.id);
this.commit();
}
@@ -195,7 +319,7 @@ export class TimerEngine {
timer.rungAtMs = null;
timer.durationMs = deltaMs;
timer.endsAtMs = this.now() + deltaMs;
cancelTimerNotification(timer.id);
cancelPhoneAlarm(timer.id);
this.schedulePhoneNotification(timer);
} else if (timer.pausedRemainingMs !== null) {
timer.pausedRemainingMs += deltaMs;
@@ -215,7 +339,7 @@ export class TimerEngine {
timer.rungAtMs = null;
timer.pausedRemainingMs = null;
timer.endsAtMs = this.now() + timer.durationMs;
cancelTimerNotification(timer.id);
cancelPhoneAlarm(timer.id);
this.schedulePhoneNotification(timer);
this.commit();
}
@@ -232,7 +356,7 @@ export class TimerEngine {
removeTimer(id: number): void {
const index = this.state.timers.findIndex((timer) => timer.id === id);
if (index < 0) return;
cancelTimerNotification(id);
acknowledgePhoneAlarm(id);
this.state.timers.splice(index, 1);
this.commit();
}
@@ -330,7 +454,7 @@ export class TimerEngine {
deleteAlarm(id: number): void {
const index = this.state.alarms.findIndex((alarm) => alarm.id === id);
if (index < 0) return;
cancelTimerNotification(id);
cancelPhoneAlarm(id);
this.state.alarms.splice(index, 1);
this.commit();
}
@@ -340,6 +464,7 @@ export class TimerEngine {
if (!alarm || alarm.ringingSinceMs === null) return;
alarm.ringingSinceMs = null;
alarm.snoozedUntilMs = this.now() + minutes * 60_000;
acknowledgePhoneAlarm(alarm.id);
this.schedulePhoneAlarm(alarm);
this.commit();
}
@@ -351,6 +476,7 @@ export class TimerEngine {
alarm.ringingSinceMs = null;
alarm.snoozedUntilMs = null;
if (alarm.days === 0) alarm.enabled = false;
acknowledgePhoneAlarm(alarm.id);
this.schedulePhoneAlarm(alarm);
this.commit();
}
@@ -381,9 +507,13 @@ export class TimerEngine {
timer.rungAtMs = timer.endsAtMs;
timer.endsAtMs = null;
changed = true;
// Late (found due after a restart): the phone rang or missed it on
// its own schedule; only a fresh expiry starts the phone flow here.
const late = now - timer.rungAtMs > RING_GRACE_MS;
fireTimerNotification(timer.id, "Timer finished", timerNotificationText(timer));
if (!late) this.startRinging({ kind: "timer", timer });
if (!late) {
ringPhoneAlarm(timer.id, "Timer finished", timerNotificationText(timer), "timer", snoozeMinutes());
this.startRinging({ kind: "timer", timer });
}
}
for (const alarm of this.state.alarms) {
if (alarm.ringingSinceMs !== null) continue;
@@ -394,13 +524,13 @@ export class TimerEngine {
alarm.lastFiredAtMs = due;
changed = true;
const late = now - due > RING_GRACE_MS;
fireTimerNotification(alarm.id, "Alarm", alarmNotificationText(alarm));
if (late) {
// Missed by too much to ring now: fall through to the next occurrence.
alarm.ringingSinceMs = null;
if (alarm.days === 0) alarm.enabled = false;
this.schedulePhoneAlarm(alarm);
} else {
ringPhoneAlarm(alarm.id, "Alarm", alarmNotificationText(alarm), "alarm", snoozeMinutes());
this.startRinging({ kind: "alarm", alarm });
}
}
@@ -492,17 +622,17 @@ export class TimerEngine {
private schedulePhoneNotification(timer: CountdownTimer): void {
if (timer.endsAtMs === null) return;
scheduleTimerNotification(timer.id, timer.endsAtMs, "Timer finished", timerNotificationText(timer));
schedulePhoneAlarm(timer.id, timer.endsAtMs, "Timer finished", timerNotificationText(timer), "timer", snoozeMinutes());
}
/** (Re)arm or cancel the phone alarm for an alarm's next occurrence. */
private schedulePhoneAlarm(alarm: Alarm): void {
const due = alarm.ringingSinceMs === null ? this.alarmDueMs(alarm, this.now()) : null;
if (due === null) {
cancelTimerNotification(alarm.id);
cancelPhoneAlarm(alarm.id);
return;
}
scheduleTimerNotification(alarm.id, due, "Alarm", alarmNotificationText(alarm));
schedulePhoneAlarm(alarm.id, due, "Alarm", alarmNotificationText(alarm), "alarm", snoozeMinutes());
}
// -------------------------------------------------------------------------
@@ -512,6 +642,7 @@ export class TimerEngine {
this.save();
this.check();
this.notify();
if (this.booted) this.refreshReliability(false);
}
private save(): void {
@@ -533,6 +664,10 @@ export class TimerEngine {
}
}
function snoozeMinutes(): number {
return Number(timersSnoozeSetting.get()) || 10;
}
function timerNotificationText(timer: CountdownTimer): string {
const duration = formatDurationWords(timer.durationMs);
return timer.label ? `${timer.label} (${duration}) is up` : `${duration} timer is up`;
+41
View File
@@ -52,6 +52,8 @@ import { getDefaultMediumFont } from "../graphics/ui-fonts";
import { wrapText } from "../graphics/textwrap";
import { rawInputEventToInputEvent, shell, type ShellInputOutcome } from "../ui/shell/shell";
import { registerSystemTools } from "../assistant/system-tools";
import { updateGlassesPresence } from "./glasses-presence";
import { timerEngine } from "../apps/timer/timer-engine";
import { registerNavigateTools } from "../assistant/navigate-tools";
import { registerRoamTools } from "../assistant/roam-tools";
import { assistantBridge } from "../assistant/bridge-client";
@@ -116,6 +118,8 @@ export type DashboardSnapshot = {
screenRecordingActive: boolean;
batteryOptimizationWarningVisible: boolean;
fontsMissingWarningVisible: boolean;
/** Why the phone may fail to ring for a set alarm; "" when nothing is wrong or armed. */
alarmReliabilityMessage: string;
/**
* True while the headless preview display is standing in for a glasses
* connection (preview-only mode): the mirror is live and interactive, but
@@ -219,6 +223,7 @@ class DashboardController {
private firmwareWarningMessage = "";
private batteryOptimizationWarningVisible = false;
private fontsMissingWarningVisible = false;
private alarmReliabilityMessage = "";
// Sticky positive: the extracted-font file doesn't vanish mid-session, so a
// successful check spares later refreshes the file read and JSON parse.
private extractedFontsConfirmed = false;
@@ -361,6 +366,7 @@ class DashboardController {
for (const app of ALL_APPS) {
app.boot?.(this.buildAppContext(app));
}
timerEngine.onChange(() => this.refreshAlarmReliabilityWarning());
this.offAndroidNotification = onAndroidNotificationPosted((notificationKey) => {
void this.handleAndroidNotificationPosted(notificationKey).catch((error) => {
this.appendLog(`notification wake failed: ${this.formatError(error)}`);
@@ -562,6 +568,7 @@ class DashboardController {
private handleWearState(wearing: boolean): void {
this.glassesWorn = wearing;
updateGlassesPresence({ worn: wearing });
this.appendLog(wearing ? "glasses wear state: ON_HEAD" : "glasses wear state: OFF_HEAD");
this.wearRemote?.schedulePublish();
if (!wearing && this.phoneLocked && lockScreenEnabledSetting.get()) {
@@ -930,6 +937,7 @@ class DashboardController {
screenRecordingActive: this.screenRecordingActive,
batteryOptimizationWarningVisible: this.batteryOptimizationWarningVisible,
fontsMissingWarningVisible: this.fontsMissingWarningVisible,
alarmReliabilityMessage: this.alarmReliabilityMessage,
previewMode: this.isPreviewDisplayActive(),
};
}
@@ -1021,9 +1029,35 @@ class DashboardController {
}
}
/**
* Mirror the Timers engine's phone self-check into the warnings modal. The
* engine re-checks on its own schedule and on every timer/alarm change;
* a page load forces a fresh check so a just-fixed setting clears at once.
*/
refreshAlarmReliabilityWarning(force = false): void {
if (force) timerEngine.refreshReliability(true);
const message = timerEngine.phoneReliabilityMessage();
if (message !== this.alarmReliabilityMessage) {
this.alarmReliabilityMessage = message;
this.emit();
}
}
openAlarmReliabilityFix(): void {
timerEngine.openPhoneReliabilityFix();
// The system screen is asynchronous with no result; poll briefly so the
// warning clears once the setting is changed.
let checksLeft = 12;
const poll = setInterval(() => {
this.refreshAlarmReliabilityWarning(true);
if (!this.alarmReliabilityMessage || --checksLeft <= 0) clearInterval(poll);
}, 5_000);
}
refreshEvenAppStatus(): void {
this.refreshBatteryOptimizationStatus();
this.refreshEvenHubFontStatus();
this.refreshAlarmReliabilityWarning(true);
const state = readEvenAppNotificationState();
const wasActive = this.evenNotificationActive;
this.evenNotificationActive = state.evenNotificationActive;
@@ -1288,6 +1322,7 @@ class DashboardController {
// the transport comes back, so do not make lock decisions from a
// stale pre-disconnect value in the meantime.
this.glassesWorn = null;
updateGlassesPresence({ worn: null });
// The mic enable was session-scoped too: park any live capture so
// the next session restarts it, instead of leaving a holder that
// makes every later request think the mic is already running.
@@ -1329,6 +1364,7 @@ class DashboardController {
headset: hasBatteryLevel ? state.battery : this.lastHeadsetBattery,
headsetCharging: state.chargingStatus > 0,
});
updateGlassesPresence({ charging: state.chargingStatus > 0 || this.phase === "charging" });
if ((this.phase === "connected" || this.phase === "charging") && this.communicator) {
// Repaint the top bar (battery indicators live in the shell chrome).
this.requestShellRender();
@@ -2453,6 +2489,11 @@ class DashboardController {
private setPhase(phase: ConnectionPhase): void {
if (this.phase === phase) return;
this.phase = phase;
// "charging" is a live BLE link with the glasses in their case.
updateGlassesPresence({
connected: phase === "connected" || phase === "charging",
charging: phase === "charging" || (shell.getBatteryLevels().headsetCharging ?? false),
});
if (phase === "disconnected") {
// Kept across "connecting": silent mode blocks app launches, so it can
// itself cause the reconnect churn, and Java re-reports it either way.
+46
View File
@@ -0,0 +1,46 @@
/**
* Whether the glasses could carry an alert right now: connected over BLE, on
* a head, and not charging. Fed by the dashboard controller from the
* transport's phase, wear-state and battery reports; consumed by the Timers
* engine, which mirrors it to the phone's alarm clock so the phone knows
* when to add its own sound.
*/
export type GlassesPresence = {
connected: boolean;
/** null until the firmware has reported a wear state this session. */
worn: boolean | null;
charging: boolean;
};
let presence: GlassesPresence = { connected: false, worn: null, charging: false };
const listeners = new Set<(presence: GlassesPresence) => void>();
export function getGlassesPresence(): GlassesPresence {
return presence;
}
/** True when a fresh, positive report says the glasses are worn and usable. */
export function glassesCanCarryAlert(current: GlassesPresence = presence): boolean {
return current.connected && current.worn === true && !current.charging;
}
export function updateGlassesPresence(patch: Partial<GlassesPresence>): void {
const next = { ...presence, ...patch };
if (next.connected === presence.connected && next.worn === presence.worn && next.charging === presence.charging) return;
presence = next;
for (const listener of Array.from(listeners)) {
try {
listener(presence);
} catch (error) {
console.warn(`glasses presence listener failed: ${error}`);
}
}
}
export function onGlassesPresenceChanged(listener: (presence: GlassesPresence) => void): () => void {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
+154
View File
@@ -0,0 +1,154 @@
import { Utils } from "@nativescript/core";
declare const com: any;
/**
* Bridge to the Java alarm clock (FaceclawAlarms / FaceclawAlarmService):
* the durable phone side of the Timers app's timers and alarms. The phone
* schedules an exact alarm-clock alarm per item, re-arms them after reboots
* and time changes, and when one comes due shows it on the phone (silently
* at first) and adds phone sound if the glasses cannot carry it. Ids are the
* engine's item ids.
*/
export type AlarmKind = "timer" | "alarm";
export type PhoneAlarmAction = { id: number; action: "dismiss" | "snooze"; minutes: number; atMs: number };
export type AlarmReliabilityIssue = { code: string; message: string; fixable: boolean };
function getContext(): android.content.Context | null {
if (!global.isAndroid) return null;
return Utils.android.getApplicationContext() ?? null;
}
/** Schedule (or move) the phone alarm that rings `title` / `text` at triggerAtMs. */
export function schedulePhoneAlarm(
itemId: number,
triggerAtMs: number,
title: string,
text: string,
kind: AlarmKind,
snoozeMinutes: number,
): void {
const context = getContext();
if (!context) return;
com.faceclaw.app.FaceclawAlarms.schedule(context, itemId, triggerAtMs, title, text, kind, snoozeMinutes);
}
/** Cancel the pending phone alarm, stop it if ringing, and clear its notification. */
export function cancelPhoneAlarm(itemId: number): void {
const context = getContext();
if (!context) return;
com.faceclaw.app.FaceclawAlarms.cancel(context, itemId);
}
/** The engine's own expiry path: start the phone ringing flow (deduplicated against the alarm's). */
export function ringPhoneAlarm(itemId: number, title: string, text: string, kind: AlarmKind, snoozeMinutes: number): void {
const context = getContext();
if (!context) return;
com.faceclaw.app.FaceclawAlarms.ring(context, itemId, title, text, kind, snoozeMinutes);
}
/** The glasses are showing the item: the phone starts its 30-second acknowledgement clock. */
export function phoneAlarmDeliveredToGlasses(itemId: number): void {
const context = getContext();
if (!context) return;
com.faceclaw.app.FaceclawAlarms.deliveredToGlasses(context, itemId);
}
/** The wearer dealt with the item on the glasses: the phone goes quiet. */
export function acknowledgePhoneAlarm(itemId: number): void {
const context = getContext();
if (!context) return;
com.faceclaw.app.FaceclawAlarms.acknowledge(context, itemId);
}
/** Tell the phone whether the glasses could carry an alarm right now. */
export function setPhoneAlarmGlassesStatus(connected: boolean, worn: boolean, charging: boolean): void {
if (!global.isAndroid) return;
com.faceclaw.app.FaceclawAlarms.setGlassesStatus(connected, worn, charging);
}
let retainedListenerProxy: any = null;
const actionListeners = new Set<(action: PhoneAlarmAction) => void>();
/** Live phone-side dismiss / snooze events (journaled ones arrive through drainPhoneAlarmJournal). */
export function onPhoneAlarmAction(listener: (action: PhoneAlarmAction) => void): () => void {
if (retainedListenerProxy === null && global.isAndroid) {
retainedListenerProxy = new com.faceclaw.app.FaceclawAlarmListener({
onPhoneAction: (id: number, action: string, minutes: number) => {
const event: PhoneAlarmAction = {
id: Number(id),
action: String(action) === "snooze" ? "snooze" : "dismiss",
minutes: Number(minutes),
atMs: Date.now(),
};
for (const registered of Array.from(actionListeners)) {
try {
registered(event);
} catch (error) {
console.warn(`phone alarm action listener failed: ${error}`);
}
}
},
});
com.faceclaw.app.FaceclawAlarms.setListener(retainedListenerProxy);
}
actionListeners.add(listener);
return () => {
actionListeners.delete(listener);
};
}
/** Phone-side actions taken while the engine was not listening, oldest first; cleared on read. */
export function drainPhoneAlarmJournal(): PhoneAlarmAction[] {
const context = getContext();
if (!context) return [];
let parsed: any;
try {
parsed = JSON.parse(String(com.faceclaw.app.FaceclawAlarms.drainJournal(context)));
} catch {
return [];
}
if (!Array.isArray(parsed)) return [];
return parsed
.filter((entry) => entry && typeof entry === "object" && Number.isFinite(Number(entry.id)))
.map((entry) => ({
id: Number(entry.id),
action: entry.action === "snooze" ? "snooze" : "dismiss",
minutes: Number(entry.minutes) || 0,
atMs: Number(entry.at) || 0,
}));
}
/** Conditions under which the phone may fail to ring, most serious first. */
export function checkPhoneAlarmReliability(): AlarmReliabilityIssue[] {
const context = getContext();
if (!context) return [];
let parsed: any;
try {
parsed = JSON.parse(String(com.faceclaw.app.FaceclawAlarms.checkReliability(context)));
} catch (error) {
console.warn(`alarm reliability check failed: ${error}`);
return [];
}
if (!Array.isArray(parsed)) return [];
return parsed
.filter((entry) => entry && typeof entry === "object" && typeof entry.code === "string")
.map((entry) => ({ code: entry.code, message: String(entry.message ?? ""), fixable: entry.fixable !== false }));
}
/** Open the system screen where a reliability issue can be fixed. */
export function openPhoneAlarmReliabilityFix(code: string): void {
const context = getContext();
if (!context) return;
com.faceclaw.app.FaceclawAlarms.openReliabilityFix(context, code);
}
/** The phone's ring / miss / action log, one line per entry, newest last. */
export function readPhoneAlarmLog(): string {
const context = getContext();
if (!context) return "";
return String(com.faceclaw.app.FaceclawAlarms.readLog(context));
}
-36
View File
@@ -1,36 +0,0 @@
import { Utils } from "@nativescript/core";
declare const com: any;
/**
* Bridge to FaceclawTimerNotifications.java: the durable Android alarm and
* phone notification behind every Timers-app expiry (countdown timers and
* alarms alike, keyed by the item's id). The phone posts the notification at
* `triggerAtMs` even if the app process is asleep or gone.
*/
function getContext(): android.content.Context | null {
if (!global.isAndroid) return null;
return Utils.android.getApplicationContext() ?? null;
}
/** Schedule (or move) the Android alarm that posts `title` / `text` at triggerAtMs. */
export function scheduleTimerNotification(itemId: number, triggerAtMs: number, title: string, text: string): void {
const context = getContext();
if (!context) return;
com.faceclaw.app.FaceclawTimerNotifications.schedule(context, itemId, triggerAtMs, title, text);
}
/** Cancel both a pending alarm and any already-posted notification. */
export function cancelTimerNotification(itemId: number): void {
const context = getContext();
if (!context) return;
com.faceclaw.app.FaceclawTimerNotifications.cancel(context, itemId);
}
/** The engine's own expiry path; Java deduplicates it against the alarm's. */
export function fireTimerNotification(itemId: number, title: string, text: string): void {
const context = getContext();
if (!context) return;
com.faceclaw.app.FaceclawTimerNotifications.fireNow(context, itemId, title, text);
}
+4
View File
@@ -96,6 +96,10 @@
<Label text="The G2 fonts have not been extracted, so EvenHub apps will render with fallback fonts. Preparing them downloads the official firmware to extract its fonts; your glasses are not reflashed." textWrap="true" />
<Button text="Prepare G2 fonts" tap="{{ onPrepareFontsTap }}" class="-primary" />
</StackLayout>
<StackLayout visibility="{{ alarmReliabilityWarningVisibility }}" class="warnings-modal-item">
<Label text="{{ alarmReliabilityMessage }}" textWrap="true" />
<Button text="Open phone settings" tap="{{ onFixAlarmReliabilityTap }}" class="-primary" />
</StackLayout>
<Button text="Close" tap="{{ onWarningsModalCloseTap }}" />
</StackLayout>
</ScrollView>
+26 -1
View File
@@ -66,6 +66,7 @@ export class MainViewModel extends Observable {
private _screenRecordingActive = false;
private _batteryOptimizationWarningVisible = false;
private _fontsMissingWarningVisible = false;
private _alarmReliabilityMessage = "";
private _warningsModalVisible = false;
private _previewMode = false;
private _phase: "disconnected" | "connecting" | "connected" | "charging" | "disconnecting" = "disconnected";
@@ -116,6 +117,7 @@ export class MainViewModel extends Observable {
this.screenRecordingActive = snapshot.screenRecordingActive;
this.batteryOptimizationWarningVisible = snapshot.batteryOptimizationWarningVisible;
this.fontsMissingWarningVisible = snapshot.fontsMissingWarningVisible;
this.alarmReliabilityMessage = snapshot.alarmReliabilityMessage;
this.refreshPadFocusLine();
}));
// Brightness / display mode can change from the glasses' Settings app too.
@@ -721,6 +723,28 @@ export class MainViewModel extends Observable {
dashboardController.requestBatteryOptimizationExemption();
}
get alarmReliabilityMessage(): string {
return this._alarmReliabilityMessage;
}
set alarmReliabilityMessage(value: string) {
if (this._alarmReliabilityMessage !== value) {
this._alarmReliabilityMessage = value;
this.notifyPropertyChange("alarmReliabilityMessage", value);
this.notifyPropertyChange("alarmReliabilityWarningVisibility", this.alarmReliabilityWarningVisibility);
this.refreshWarningIndicator();
}
}
get alarmReliabilityWarningVisibility(): "visible" | "collapse" {
return this._alarmReliabilityMessage ? "visible" : "collapse";
}
onFixAlarmReliabilityTap(): void {
this.setWarningsModalVisible(false);
dashboardController.openAlarmReliabilityFix();
}
// ---- the action bar's warning triangle and the modal behind it ----
get anyWarningVisible(): boolean {
@@ -728,7 +752,8 @@ export class MainViewModel extends Observable {
this._evenAppConflictWarningVisible ||
this._firmwareWarningVisible ||
this._batteryOptimizationWarningVisible ||
this._fontsMissingWarningVisible
this._fontsMissingWarningVisible ||
this._alarmReliabilityMessage.length > 0
);
}