Files
faceclaw/app/g2/android-permissions.ts
T
James Babcock 97fad7ae2b Add Permissions screen to the onboarding flow, replacing scattered permissions prompts happening later
<details>
<summary>Prompts Used</summary>
Let's add a Permissions screen, to concentrate the various Android permissions requests. This will be shown during onboarding, in between the "Before You Continue" screen and the "Custom Firmware Required" screen. There will also be a "Permissions" menu item in the main screen menu.

Each permission will be a card, styled similarly to the device-selection cards on the Pair Your Glasses screen. Each card will have the title for the permission, some text explaining what the permission is used for, and a checkmark if the permission is already present. The permissions needed are:

Nearby Devices: Needed to communicate with your smart glasses over bluetooth
Send Notifications: A notification will be pinned, to keep Faceclaw running while your phone screen is off.
Battery Optimization: Needed to keep running while your phone screen is off.
Read Notifications: (Optional) Needed to display your Android notification on the glasses.
Microphone: (Optional) Needed to use voice input.
Location: (Optional) Needed to use location-based features like navigation inside glasses apps.
Calendar: (Optional) Needed to display your calendar on the glasses.

> Done — the Permissions screen is in place, builds cleanly, and all the permissions it requests were already declared in the manifest.
>
> **What was added:**
>
> - **New screen** (`app/phone-ui/permissions-page.{xml,ts}` + `permissions-view-model.ts`): one card per permission, reusing the pairing page's card styling (`pairing-row`, `pairing-title`, `pairing-badge`) so they match the device-selection cards. Each card shows the title, the explanation text you specified, and a green ✓ when granted. Tapping an ungranted card launches its grant flow; granted cards ignore taps. The four optional permissions get an "Optional" badge (matching the pairing page's badge style) instead of a "(Optional)" text prefix.
> - **Onboarding wiring**: "Agree" on Before You Continue now navigates to the permissions page, and its "Next" button navigates forward to a fresh onboarding page starting at the Custom Firmware Required step (`onboarding-page.ts` now accepts a `step` context; `OnboardingViewModel` takes an initial step). "Back" returns to the disclaimer.
> - **Main menu**: a "Permissions" popup item on the main page opens the same screen in standalone mode — action bar shown, single "Done" button.
> - **Permission plumbing** (`app/g2/android-permissions.ts`): new granular helpers — `hasBlePermissions`/`requestBlePermissions` (BLE only, split out of the old combined BLE+notifications request), `hasPostNotificationsPermission`/`requestPostNotificationsPermission` (reports granted pre-Android 13, where no runtime permission exists), and `hasMicrophonePermission`/`requestMicrophonePermission`. Existing `ensureBlePermissions` behavior is unchanged for its current callers.
>
> Two of the cards — Battery Optimization and Read Notifications — aren't runtime permissions; they open system screens (the existing `battery-optimization.ts` and `notification-access.ts` natives). Since Android reports their state only on return, the page re-checks all statuses on `Application.resume` (listener attached on page load, detached on unload) so checkmarks appear when you come back.
>
> Two judgment calls worth flagging: the Location checkmark tracks **fine** location (navigation needs precise fixes — "approximate only" leaves it unchecked and re-tappable), and I wrote "your Android notifications" (plural) in the Read Notifications card. This is all hardware-test pending, as usual — the flows to exercise are onboarding step 2 → Permissions → step 3, each card's grant dialog, and the resume-refresh after the battery/notification-access settings detours.
<hr>
Thanks. Let's make it so that the Continue button looks grayed out if you haven't selected all of the required permissions. It will still be active in this case, but will open a "You haven't enabled all of the necessary permissions. Are you sure you want to continue?" prompt. Also, let's add 8px of extra margin between the permission titles and the Optional badge.

> Both changes are in and the build passes.
>
> - **Grayed-out Continue**: the onboarding primary button now binds a `primaryClass` — while any of the three required permissions (Nearby Devices, Send Notifications, Battery Optimization) is missing, it gets a `permissions-primary-dimmed` class (opacity 0.45) so it looks disabled while staying tappable. Tapping it in that state shows a confirm dialog — "You haven't enabled all of the necessary permissions. Are you sure you want to continue?" with Continue/Go Back buttons — and only proceeds to the firmware step on Continue. The class re-evaluates on every refresh, so granting the last required permission un-dims the button immediately. I also renamed the onboarding label from "Next" to "Continue" to match how you referred to it (and the pairing page's onboarding button). Menu mode's "Done" never dims, since there's nothing to warn about when just closing the screen.
> - **Badge spacing**: the "Optional" badge's left margin went from the `m-l-6` class to an explicit `marginLeft="14"` (+8), set inline since the theme doesn't generate an `m-l-14` class.
</details>
2026-08-25 11:28:53 -07:00

245 lines
8.1 KiB
TypeScript

import { Application, Utils } from "@nativescript/core";
const PERMISSION_REQUEST_CODE = 4242;
const VOICE_PERMISSION_REQUEST_CODE = 4243;
const CALENDAR_PERMISSION_REQUEST_CODE = 4244;
const LOCATION_PERMISSION_REQUEST_CODE = 4245;
const FINE_LOCATION_PERMISSION_REQUEST_CODE = 4246;
const BLE_ONLY_PERMISSION_REQUEST_CODE = 4247;
const POST_NOTIFICATIONS_PERMISSION_REQUEST_CODE = 4248;
const POST_NOTIFICATIONS_PERMISSION = "android.permission.POST_NOTIFICATIONS";
const RECORD_AUDIO_PERMISSION = "android.permission.RECORD_AUDIO";
const READ_CALENDAR_PERMISSION = "android.permission.READ_CALENDAR";
const ACCESS_COARSE_LOCATION_PERMISSION = "android.permission.ACCESS_COARSE_LOCATION";
const ACCESS_FINE_LOCATION_PERMISSION = "android.permission.ACCESS_FINE_LOCATION";
function getActivity(): androidx.appcompat.app.AppCompatActivity {
const activity = Application.android.foregroundActivity ?? Application.android.startActivity;
if (!activity) throw new Error("No Android activity is available");
return activity;
}
function getContext(): android.content.Context {
const context = Utils.android.getApplicationContext();
if (!context) throw new Error("No Android application context is available");
return context;
}
function toJavaStringArray(values: string[]): string[] {
const result = Array.create("java.lang.String", values.length) as string[];
for (let i = 0; i < values.length; i++) {
result[i] = values[i]!;
}
return result;
}
/** The runtime permissions this Android version needs for BLE scan + connect. */
function getBlePermissions(): string[] {
if (android.os.Build.VERSION.SDK_INT >= 31) {
return [
android.Manifest.permission.BLUETOOTH_SCAN,
android.Manifest.permission.BLUETOOTH_CONNECT,
];
}
return [android.Manifest.permission.ACCESS_FINE_LOCATION];
}
function getRequiredPermissions(): string[] {
const permissions = getBlePermissions();
if (android.os.Build.VERSION.SDK_INT >= 33) {
permissions.push(POST_NOTIFICATIONS_PERMISSION);
}
return permissions;
}
function isPermissionGranted(permission: string): boolean {
const context = getContext();
return androidx.core.content.ContextCompat.checkSelfPermission(context, permission) ===
android.content.pm.PackageManager.PERMISSION_GRANTED;
}
async function ensurePermissions(
permissions: string[],
requestCode: number,
denialLabel: string,
): Promise<void> {
if (!global.isAndroid) return;
const activity = getActivity();
const missing = permissions.filter((permission) => !isPermissionGranted(permission));
if (missing.length === 0) return;
await new Promise<void>((resolve, reject) => {
const callback = (args: {
requestCode: number;
permissions: string[];
grantResults: number[];
}) => {
if (args.requestCode !== requestCode) return;
Application.android.off(Application.android.activityRequestPermissionsEvent, callback);
const denied = missing.filter(
(_permission, index) =>
args.grantResults[index] !== android.content.pm.PackageManager.PERMISSION_GRANTED,
);
if (denied.length > 0) {
reject(new Error(`${denialLabel} permissions denied: ${denied.join(", ")}`));
return;
}
resolve();
};
Application.android.on(Application.android.activityRequestPermissionsEvent, callback);
androidx.core.app.ActivityCompat.requestPermissions(
activity,
toJavaStringArray(missing),
requestCode,
);
});
}
export async function ensureBlePermissions(): Promise<void> {
await ensurePermissions(getRequiredPermissions(), PERMISSION_REQUEST_CODE, "Bluetooth");
}
export async function ensureVoicePermissions(): Promise<void> {
await ensurePermissions([RECORD_AUDIO_PERMISSION], VOICE_PERMISSION_REQUEST_CODE, "Voice control");
}
/** Whether the BLE scan/connect permissions have been granted (false off-Android). */
export function hasBlePermissions(): boolean {
if (!global.isAndroid) return false;
return getBlePermissions().every((permission) => isPermissionGranted(permission));
}
/**
* Prompt for just the BLE permissions (without POST_NOTIFICATIONS, which the
* Permissions screen presents as its own card). Resolves true when granted.
*/
export async function requestBlePermissions(): Promise<boolean> {
if (!global.isAndroid) return false;
try {
await ensurePermissions(getBlePermissions(), BLE_ONLY_PERMISSION_REQUEST_CODE, "Bluetooth");
return true;
} catch {
return false;
}
}
/**
* Whether posting notifications is allowed. Before Android 13 (sdk 33) there
* is no runtime permission for this, so it reports as granted.
*/
export function hasPostNotificationsPermission(): boolean {
if (!global.isAndroid) return false;
if (android.os.Build.VERSION.SDK_INT < 33) return true;
return isPermissionGranted(POST_NOTIFICATIONS_PERMISSION);
}
/** Prompt for POST_NOTIFICATIONS. Resolves true when the permission is held afterward. */
export async function requestPostNotificationsPermission(): Promise<boolean> {
if (!global.isAndroid) return false;
if (android.os.Build.VERSION.SDK_INT < 33) return true;
try {
await ensurePermissions(
[POST_NOTIFICATIONS_PERMISSION],
POST_NOTIFICATIONS_PERMISSION_REQUEST_CODE,
"Notification",
);
return true;
} catch {
return false;
}
}
/** Whether RECORD_AUDIO has been granted (false off-Android). */
export function hasMicrophonePermission(): boolean {
if (!global.isAndroid) return false;
return isPermissionGranted(RECORD_AUDIO_PERMISSION);
}
/** Prompt for RECORD_AUDIO. Resolves true when granted, false on denial. */
export async function requestMicrophonePermission(): Promise<boolean> {
if (!global.isAndroid) return false;
try {
await ensureVoicePermissions();
return true;
} catch {
return false;
}
}
/** Whether READ_CALENDAR has been granted (false off-Android). */
export function hasCalendarPermission(): boolean {
if (!global.isAndroid) return false;
return isPermissionGranted(READ_CALENDAR_PERMISSION);
}
/**
* Prompt for READ_CALENDAR if not already granted. Resolves true when the
* permission is held afterward, false if the user denied it (or no activity
* was available to show the prompt).
*/
export async function ensureCalendarPermission(): Promise<boolean> {
if (!global.isAndroid) return false;
try {
await ensurePermissions([READ_CALENDAR_PERMISSION], CALENDAR_PERMISSION_REQUEST_CODE, "Calendar");
return true;
} catch {
return false;
}
}
/** Whether precise (GPS) foreground location access has been granted. */
export function hasFineLocationPermission(): boolean {
if (!global.isAndroid) return false;
return isPermissionGranted(ACCESS_FINE_LOCATION_PERMISSION);
}
/**
* Prompt for precise foreground location access (navigation needs GPS fixes
* with bearing). Requests coarse alongside fine so Android's "approximate
* only" choice degrades gracefully rather than denying outright; resolves
* true only when precise access is actually held.
*/
export async function ensureFineLocationPermission(): Promise<boolean> {
if (!global.isAndroid) return false;
try {
await ensurePermissions(
[ACCESS_FINE_LOCATION_PERMISSION, ACCESS_COARSE_LOCATION_PERMISSION],
FINE_LOCATION_PERMISSION_REQUEST_CODE,
"Location",
);
} catch {
// Fall through: the user may have granted approximate-only, which still
// reports as a denial of fine. Re-check what is actually held.
}
return hasFineLocationPermission();
}
/** Whether approximate foreground location access has been granted. */
export function hasLocationPermission(): boolean {
if (!global.isAndroid) return false;
return isPermissionGranted(ACCESS_COARSE_LOCATION_PERMISSION);
}
/**
* Prompt for approximate foreground location access. Weather only needs a
* coarse coordinate, which avoids asking for more precise access than needed.
*/
export async function ensureLocationPermission(): Promise<boolean> {
if (!global.isAndroid) return false;
try {
await ensurePermissions(
[ACCESS_COARSE_LOCATION_PERMISSION],
LOCATION_PERMISSION_REQUEST_CODE,
"Location",
);
return true;
} catch {
return false;
}
}