Add Timer, Weather apps; build out UI of music app; add wakeword action setting

This commit is contained in:
James Babcock committed 2026-07-20 02:04:21 -07:00
1 parent 008f2277ca
commit 5c73ba2a4d
27 files changed
+2181 -312

No files matched your search

@@ -19,9 +19,12 @@
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" android:maxSdkVersion="30"/>
<!-- Approximate foreground location is sufficient for the Weather app. -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<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"/>
<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"/>
@@ -87,5 +90,9 @@
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
<receiver
android:name="com.faceclaw.app.FaceclawTimerReceiver"
android:enabled="true"
android:exported="false" />
</application>
</manifest>
@@ -0,0 +1,8 @@
package com.faceclaw.app;
/** One-shot Android location callbacks for the TypeScript Weather bridge. */
public interface FaceclawLocationListener {
void onLocation(double latitude, double longitude, float accuracyMeters, long timestampMs);
void onError(String message);
}
@@ -0,0 +1,196 @@
package com.faceclaw.app;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import androidx.core.content.ContextCompat;
import java.util.List;
/**
* One-shot, foreground-only location lookup for Weather. It prefers a fresh
* coarse network fix, but can fall back to the newest cached provider fix if
* Android cannot produce a new location before the timeout.
*/
public final class FaceclawLocationProvider implements LocationListener {
private static final long FRESH_CACHE_MS = 10L * 60L * 1000L;
private static final long MAX_CACHE_MS = 24L * 60L * 60L * 1000L;
private static final long TIMEOUT_MS = 15L * 1000L;
private final Context context;
private final LocationManager locationManager;
private final Handler mainHandler = new Handler(Looper.getMainLooper());
private final Runnable timeout = this::onTimeout;
private FaceclawLocationListener listener;
private Location cachedLocation;
private boolean running;
public FaceclawLocationProvider(Context context) {
this.context = context.getApplicationContext();
this.locationManager = (LocationManager) this.context.getSystemService(Context.LOCATION_SERVICE);
}
public void setListener(FaceclawLocationListener listener) {
this.listener = listener;
}
public void start() {
mainHandler.post(this::startOnMainThread);
}
public void cancel() {
mainHandler.post(() -> finish(null, null));
}
private void startOnMainThread() {
if (running) {
return;
}
if (locationManager == null) {
deliverError("Android location service is unavailable.");
return;
}
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
deliverError("Location permission is required.");
return;
}
cachedLocation = newestCachedLocation();
if (isRecent(cachedLocation, FRESH_CACHE_MS)) {
deliverLocation(cachedLocation);
return;
}
String provider = chooseProvider();
if (provider == null) {
if (isRecent(cachedLocation, MAX_CACHE_MS)) {
deliverLocation(cachedLocation);
} else {
deliverError("Turn on Location on your phone, then retry.");
}
return;
}
try {
running = true;
locationManager.requestSingleUpdate(provider, this, Looper.getMainLooper());
mainHandler.postDelayed(timeout, TIMEOUT_MS);
} catch (SecurityException error) {
finish(null, "Location permission is required.");
} catch (Throwable error) {
finish(null, "Unable to request the current location.");
}
}
private String chooseProvider() {
try {
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
return LocationManager.NETWORK_PROVIDER;
}
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setPowerRequirement(Criteria.POWER_LOW);
return locationManager.getBestProvider(criteria, true);
} catch (Throwable ignored) {
return null;
}
}
private Location newestCachedLocation() {
Location newest = null;
try {
List<String> providers = locationManager.getProviders(true);
for (String provider : providers) {
Location candidate = locationManager.getLastKnownLocation(provider);
if (candidate != null && (newest == null || candidate.getTime() > newest.getTime())) {
newest = candidate;
}
}
} catch (SecurityException ignored) {
// The explicit permission check above owns the user-facing error.
} catch (Throwable ignored) {
// A fresh request may still succeed even if cached providers fail.
}
return newest;
}
private static boolean isRecent(Location location, long maximumAgeMs) {
return location != null
&& location.getTime() > 0L
&& System.currentTimeMillis() - location.getTime() <= maximumAgeMs;
}
private void onTimeout() {
if (isRecent(cachedLocation, MAX_CACHE_MS)) {
finish(cachedLocation, null);
} else {
finish(null, "Couldn't get your current location. Tap to retry.");
}
}
@Override
public void onLocationChanged(Location location) {
finish(location, null);
}
@Override
public void onProviderDisabled(String provider) {
// Keep waiting: Android may still deliver a queued fix or the timeout
// can fall back to another provider's cached location.
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
@SuppressWarnings("deprecation")
public void onStatusChanged(String provider, int status, Bundle extras) {
}
private void finish(Location location, String error) {
if (running) {
try {
locationManager.removeUpdates(this);
} catch (Throwable ignored) {
}
}
running = false;
mainHandler.removeCallbacks(timeout);
if (location != null) {
deliverLocation(location);
} else if (error != null) {
deliverError(error);
}
}
private void deliverLocation(Location location) {
FaceclawLocationListener current = listener;
if (current != null && location != null) {
current.onLocation(
location.getLatitude(),
location.getLongitude(),
location.hasAccuracy() ? location.getAccuracy() : -1f,
location.getTime());
}
}
private void deliverError(String message) {
FaceclawLocationListener current = listener;
if (current != null) {
current.onError(message);
}
}
}
@@ -3,7 +3,10 @@ package com.faceclaw.app;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaDescription;
import android.media.MediaMetadata;
import android.media.session.MediaController;
@@ -12,6 +15,7 @@ import android.media.session.MediaSessionManager;
import android.media.session.PlaybackState;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.provider.Settings;
import android.util.Log;
@@ -26,6 +30,7 @@ public class FaceclawMediaController {
private final Handler mainHandler = new Handler(Looper.getMainLooper());
private final ComponentName listenerComponent;
private final MediaSessionManager sessionManager;
private final AudioManager audioManager;
private final MediaController.Callback controllerCallback = new MediaController.Callback() {
@Override
@@ -71,6 +76,7 @@ public class FaceclawMediaController {
this.appContext = context.getApplicationContext();
this.listenerComponent = new ComponentName(appContext, FaceclawMediaNotificationListenerService.class);
this.sessionManager = (MediaSessionManager) appContext.getSystemService(Context.MEDIA_SESSION_SERVICE);
this.audioManager = (AudioManager) appContext.getSystemService(Context.AUDIO_SERVICE);
}
public void setListener(FaceclawMediaControllerListener listener) {
@@ -171,6 +177,30 @@ public class FaceclawMediaController {
}
}
/** Current phone media-stream volume normalized to the range 0..100. */
public int getMediaVolumePercent() {
if (audioManager == null) {
return -1;
}
int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
if (maxVolume <= 0) {
return 0;
}
int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
return Math.max(0, Math.min(100, Math.round(currentVolume * 100f / maxVolume)));
}
/** Set the phone media-stream volume from a normalized 0..100 value. */
public void setMediaVolumePercent(int volumePercent) {
if (audioManager == null) {
return;
}
int clampedPercent = Math.max(0, Math.min(100, volumePercent));
int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int streamVolume = Math.round(clampedPercent * maxVolume / 100f);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, streamVolume, 0);
}
/**
* Album art for the active session's current item, grayscale, scaled to
* fit within maxSize x maxSize preserving aspect. Returns
@@ -352,9 +382,13 @@ public class FaceclawMediaController {
String playbackState = started ? "idle" : "stopped";
String packageName = "";
String appName = "";
String title = "";
String artist = "";
String album = "";
long positionMs = -1L;
long durationMs = -1L;
float playbackSpeed = 0f;
boolean canPlayPause = false;
boolean canSkipNext = false;
boolean canSkipPrevious = false;
@@ -368,6 +402,7 @@ public class FaceclawMediaController {
status = "No active media session.";
} else {
packageName = safe(activeController.getPackageName());
appName = getApplicationLabel(packageName);
PlaybackState state = activeController.getPlaybackState();
MediaMetadata metadata = activeController.getMetadata();
playbackState = playbackStateName(state);
@@ -375,6 +410,14 @@ public class FaceclawMediaController {
title = safe(metadata.getString(MediaMetadata.METADATA_KEY_TITLE));
artist = safe(metadata.getString(MediaMetadata.METADATA_KEY_ARTIST));
album = safe(metadata.getString(MediaMetadata.METADATA_KEY_ALBUM));
durationMs = metadata.getLong(MediaMetadata.METADATA_KEY_DURATION);
if (durationMs <= 0L) {
durationMs = -1L;
}
}
if (state != null) {
positionMs = estimatedPositionMs(state, durationMs);
playbackSpeed = state.getPlaybackSpeed();
}
long actions = state == null ? 0L : state.getActions();
canPlayPause = (actions & PlaybackState.ACTION_PLAY_PAUSE) != 0
@@ -387,9 +430,13 @@ public class FaceclawMediaController {
final String finalPlaybackState = playbackState;
final String finalPackageName = packageName;
final String finalAppName = appName;
final String finalTitle = title;
final String finalArtist = artist;
final String finalAlbum = album;
final long finalPositionMs = positionMs;
final long finalDurationMs = durationMs;
final float finalPlaybackSpeed = playbackSpeed;
final boolean finalCanPlayPause = canPlayPause;
final boolean finalCanSkipNext = canSkipNext;
final boolean finalCanSkipPrevious = canSkipPrevious;
@@ -399,9 +446,13 @@ public class FaceclawMediaController {
mainHandler.post(() -> currentListener.onStateChange(
finalPlaybackState,
finalPackageName,
finalAppName,
finalTitle,
finalArtist,
finalAlbum,
finalPositionMs,
finalDurationMs,
finalPlaybackSpeed,
finalCanPlayPause,
finalCanSkipNext,
finalCanSkipPrevious,
@@ -429,6 +480,39 @@ public class FaceclawMediaController {
}
}
/** PlaybackState positions are snapshots; advance a playing snapshot to now. */
private long estimatedPositionMs(PlaybackState state, long durationMs) {
long positionMs = state.getPosition();
if (positionMs == PlaybackState.PLAYBACK_POSITION_UNKNOWN) {
return -1L;
}
if (state.getState() == PlaybackState.STATE_PLAYING) {
long updatedAtMs = state.getLastPositionUpdateTime();
if (updatedAtMs > 0L) {
positionMs += (long) ((SystemClock.elapsedRealtime() - updatedAtMs) * state.getPlaybackSpeed());
}
}
positionMs = Math.max(0L, positionMs);
return durationMs > 0L ? Math.min(positionMs, durationMs) : positionMs;
}
/** Resolve a media session's package id to the user-facing installed app name. */
private String getApplicationLabel(String packageName) {
if (packageName == null || packageName.isEmpty()) {
return "";
}
PackageManager packageManager = appContext.getPackageManager();
try {
ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName, 0);
CharSequence label = packageManager.getApplicationLabel(applicationInfo);
if (label != null && label.length() > 0) {
return label.toString();
}
} catch (PackageManager.NameNotFoundException ignored) {
}
return packageName;
}
private String safe(String value) {
return value == null ? "" : value;
}
@@ -4,9 +4,13 @@ public interface FaceclawMediaControllerListener {
void onStateChange(
String playbackState,
String packageName,
String appName,
String title,
String artist,
String album,
long positionMs,
long durationMs,
float playbackSpeed,
boolean canPlayPause,
boolean canSkipNext,
boolean canSkipPrevious,
@@ -388,7 +388,11 @@ public class FaceclawMediaNotificationListenerService extends NotificationListen
if (statusBarNotification == null || statusBarNotification.getNotification() == null) {
return false;
}
if (service.getPackageName().equals(statusBarNotification.getPackageName())) {
// The dashboard's own persistent foreground notification is noise, but
// Timer expiry notifications deliberately flow through the same mirror
// and modal path as notifications from other Android apps.
if (service.getPackageName().equals(statusBarNotification.getPackageName())
&& !FaceclawTimerNotifications.isTimerNotification(statusBarNotification)) {
return false;
}
Notification notification = statusBarNotification.getNotification();
@@ -0,0 +1,187 @@
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 Timer app. */
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_DURATION_LABEL = "durationLabel";
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 worker 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 durationLabel) {
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, durationLabel);
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();
}
/** Worker-timeout path. Cancels the backup alarm and posts at most once. */
public static void fireNow(Context context, long timerId, String durationLabel) {
Context appContext = context.getApplicationContext();
AlarmManager alarmManager = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
if (alarmManager != null) {
alarmManager.cancel(expiryPendingIntent(appContext, timerId, durationLabel));
}
showExpiredOnce(appContext, timerId, durationLabel);
}
static synchronized void showExpiredOnce(Context context, long timerId, String durationLabel) {
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 label = durationLabel == null || durationLabel.trim().isEmpty() ? "Timer" : durationLabel + " timer";
Notification notification = builder
.setContentTitle("Timer finished")
.setContentText(label + " is up")
.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);
}
}
/** Only Timer notifications from our own package should enter the mirror. */
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 durationLabel
) {
Intent intent = new Intent(context, FaceclawTimerReceiver.class);
intent.setAction(ACTION_EXPIRE);
intent.putExtra(EXTRA_TIMER_ID, timerId);
intent.putExtra(EXTRA_DURATION_LABEL, durationLabel == null ? "" : durationLabel);
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;
}
}
@@ -0,0 +1,21 @@
package com.faceclaw.app;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/** Receives durable timer alarms even if the NativeScript worker 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 durationLabel = intent.getStringExtra(FaceclawTimerNotifications.EXTRA_DURATION_LABEL);
FaceclawTimerNotifications.showExpiredOnce(context, timerId, durationLabel);
}
}