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

@@ -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);
}
}