Files
swiftcontrol/lib/utils/requirements/android.dart
Jonas Acker bea8a77a25 fix(android): no crash when Android restarts the keep-alive service
The service was started with START_REDELIVER_INTENT. After Android killed
the process, it restarted the service in the background, where
startForeground is refused (ForegroundServiceStartNotAllowedException).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 07:16:44 +01:00

371 lines
14 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'dart:async';
import 'dart:io';
import 'dart:isolate';
import 'dart:ui';
import 'package:bike_control/gen/l10n.dart';
import 'package:bike_control/main.dart' show recordError;
import 'package:bike_control/utils/actions/android.dart';
import 'package:bike_control/utils/core.dart';
import 'package:bike_control/utils/requirements/platform.dart';
import 'package:bike_control/widgets/accessibility_disclosure_dialog.dart';
import 'package:bike_control/widgets/ui/toast.dart';
import 'package:flutter/services.dart';
import 'package:bike_control/pages/rides/ride_details_page.dart' show openRideFromNotification;
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart';
import 'package:universal_ble/universal_ble.dart';
import 'package:url_launcher/url_launcher_string.dart';
class AccessibilityRequirement extends PlatformRequirement {
AccessibilityRequirement()
: super(
AppLocalizations.current.allowAccessibilityService,
description: AppLocalizations.current.accessibilityDescription,
icon: LucideIcons.personStanding,
);
@override
Future<void> call(BuildContext context, VoidCallback onUpdate) async {
// Only meaningful while the local (AndroidActions) handler is active. When
// connected to a trainer app on another device the handler is a
// RemoteActions, and the accessibility service does not apply.
if (core.actionHandler is! AndroidActions) return;
await _showDisclosureDialog(context, onUpdate);
await getStatus();
}
@override
Future<bool> getStatus() async {
// Guard the cast: on Android, connecting to a trainer app on another device
// makes actionHandler a RemoteActions, so a blind `as AndroidActions` here
// threw a TypeError (e.g. from the Network Troubleshooting "enable Local"
// fix, which checks this requirement regardless of the active handler).
final handler = core.actionHandler;
if (handler is! AndroidActions) {
status = false;
return status;
}
status = await handler.accessibilityHandler.hasPermission();
return status;
}
Future<void> _showDisclosureDialog(BuildContext context, VoidCallback onUpdate) async {
return showDialog<void>(
context: context,
barrierDismissible: false, // Prevent dismissing by tapping outside
builder: (BuildContext context) {
return AccessibilityDisclosureDialog(
onAccept: () {
Navigator.of(context).pop();
// Open accessibility settings after user consents
(core.actionHandler as AndroidActions).accessibilityHandler.openPermissions().then((_) async {
await getStatus();
onUpdate();
});
},
onDeny: () async {
await getStatus();
Navigator.of(context).pop();
// User denied, no action taken
},
);
},
);
}
}
class BluetoothScanRequirement extends PlatformRequirement {
BluetoothScanRequirement() : super(AppLocalizations.current.allowBluetoothScan, icon: LucideIcons.bluetoothSearching);
@override
Future<void> call(BuildContext context, VoidCallback onUpdate) async {
await Permission.bluetoothScan.request();
await getStatus();
}
@override
Future<bool> getStatus() async {
final state = await Permission.bluetoothScan.status;
status = state.isGranted || state.isLimited;
return status;
}
}
class LocationRequirement extends PlatformRequirement {
LocationRequirement() : super(AppLocalizations.current.allowLocationForBluetooth, icon: LucideIcons.mapPin);
@override
Future<void> call(BuildContext context, VoidCallback onUpdate) async {
await Permission.locationWhenInUse.request();
await getStatus();
}
@override
Future<bool> getStatus() async {
final state = await Permission.locationWhenInUse.status;
status = state.isGranted || state.isLimited;
return status;
}
}
class BluetoothConnectRequirement extends PlatformRequirement {
BluetoothConnectRequirement()
: super(AppLocalizations.current.allowBluetoothConnections, icon: LucideIcons.bluetoothConnected);
@override
Future<void> call(BuildContext context, VoidCallback onUpdate) async {
await Permission.bluetoothConnect.request();
await getStatus();
}
@override
Future<bool> getStatus() async {
final state = await Permission.bluetoothConnect.status;
status = state.isGranted || state.isLimited;
return status;
}
}
ReceivePort? _receivePort;
StreamSubscription? _sub;
class NotificationRequirement extends PlatformRequirement {
NotificationRequirement()
: super(
AppLocalizations.current.allowPersistentNotification,
description: AppLocalizations.current.notificationDescription,
icon: LucideIcons.bellRing,
);
@override
Future<void> call(BuildContext context, VoidCallback onUpdate) async {
if (Platform.isAndroid) {
final result = await core.flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()
?.requestNotificationsPermission();
if (result == false) {
buildToast(
title: AppLocalizations.current.enableNotificationsAndroid,
);
}
} else if (Platform.isIOS) {
final result = await core.flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>()
?.requestPermissions(
alert: true,
badge: false,
sound: false,
);
core.settings.setHasAskedPermissions(true);
if (result == false) {
buildToast(
title: AppLocalizations.current.enableNotificationsApple,
);
launchUrlString('x-apple.systempreferences:com.apple.preference.notifications');
}
} else if (Platform.isMacOS) {
final result = await core.flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<MacOSFlutterLocalNotificationsPlugin>()
?.requestPermissions(
alert: true,
badge: false,
sound: false,
);
core.settings.setHasAskedPermissions(true);
if (result == false) {
buildToast(
title: AppLocalizations.current.enableNotificationsApple,
);
launchUrlString('x-apple.systempreferences:com.apple.preference.notifications');
}
}
await getStatus();
return;
}
@override
Future<bool> getStatus() async {
if (Platform.isAndroid) {
final bool granted =
await core.flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()
?.areNotificationsEnabled() ??
false;
status = granted;
} else if (Platform.isIOS) {
final permissions = await core.flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>()
?.checkPermissions();
status = permissions?.isEnabled == true || core.settings.hasAskedPermissions();
} else if (Platform.isMacOS) {
final permissions = await core.flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<MacOSFlutterLocalNotificationsPlugin>()
?.checkPermissions();
status = permissions?.isEnabled == true || core.settings.hasAskedPermissions();
} else {
status = true;
}
return status;
}
static Future<void> setup() async {
print('NOTIFICATION SETUP');
// macOS has no background-isolate support for notification responses, and
// registering that callback there is the prime suspect for the startup
// hang some macOS users hit — so only wire the background handler off
// macOS. Foreground responses still route through the same handler.
await core.flutterLocalNotificationsPlugin.initialize(
settings: InitializationSettings(
android: AndroidInitializationSettings(
'@drawable/ic_notification',
),
iOS: DarwinInitializationSettings(
requestAlertPermission: false,
requestBadgePermission: false,
requestSoundPermission: false,
),
macOS: DarwinInitializationSettings(
requestAlertPermission: false,
),
windows: WindowsInitializationSettings(
appName: 'BikeControl',
appUserModelId: 'OpenBikeControl.BikeControl',
guid: '00000012-0000-1000-8000-00805f9b34fb',
),
linux: LinuxInitializationSettings(
defaultActionName: 'Open BikeControl',
),
),
onDidReceiveBackgroundNotificationResponse: Platform.isMacOS ? null : notificationTapBackground,
onDidReceiveNotificationResponse: (n) {
notificationTapBackground(n);
// A ride's push opens that ride's Details.
if (n.actionId == null) unawaited(openRideFromNotification(n.payload));
},
);
// The app was started by tapping a ride's push: open it once the first
// screen stands.
// Not implemented on Linux, where a notification can't launch the app.
final launch = Platform.isLinux
? null
: await core.flutterLocalNotificationsPlugin.getNotificationAppLaunchDetails();
final payload = launch?.didNotificationLaunchApp == true ? launch?.notificationResponse?.payload : null;
if (payload != null) {
WidgetsBinding.instance.addPostFrameCallback((_) => unawaited(openRideFromNotification(payload)));
}
}
/// Closes every connection, drops the keep-alive foreground service and its
/// notification, then leaves the app. Popping alone only finishes the
/// activity — the service would keep the process and notification alive.
static Future<void> closeAndQuit() async {
UniversalBle.onAvailabilityChange = null;
// A disconnect that hangs or throws must not keep the app and its
// notification alive: each step gets a deadline, and quitting goes on.
await _quitStep('disconnect all', core.connection.disconnectAll);
await _quitStep('action cleanup', () async => core.actionHandler.cleanup());
await _quitStep('stop connection', core.connection.stop);
if (Platform.isAndroid) {
final android = AndroidFlutterLocalNotificationsPlugin();
await _quitStep('stop foreground service', android.stopForegroundService);
await _quitStep('cancel notifications', android.cancelAll);
}
await SystemNavigator.pop();
}
static Future<void> _quitStep(String name, Future<void> Function() step) async {
try {
await step().timeout(_quitStepTimeout);
} catch (e, s) {
unawaited(recordError(e, s, context: 'close and quit: $name'));
}
}
static const _quitStepTimeout = Duration(seconds: 3);
static Future<void> addPersistentNotification() async {
const String channelGroupId = 'BikeControl';
// create the group first
await core.flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()!
.createNotificationChannelGroup(
AndroidNotificationChannelGroup(channelGroupId, channelGroupId, description: 'Keep Alive'),
);
// create channels associated with the group
await core.flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()!
.createNotificationChannel(
const AndroidNotificationChannel(
channelGroupId,
channelGroupId,
description: 'Keep Alive',
groupId: channelGroupId,
),
);
await AndroidFlutterLocalNotificationsPlugin().startForegroundService(
id: 1,
title: channelGroupId,
body: AppLocalizations.current.allowsRunningInBackground,
foregroundServiceTypes: {AndroidServiceForegroundType.foregroundServiceTypeConnectedDevice},
// Not sticky: when Android kills the process, a redelivered intent restarts
// the service in the background, where startForeground is refused
// (ForegroundServiceStartNotAllowedException) and the app crashes. A restarted
// service has no engine or BLE connections anyway.
startType: AndroidServiceStartType.startNotSticky,
notificationDetails: AndroidNotificationDetails(
channelGroupId,
'Keep Alive',
actions: [
AndroidNotificationAction(
'disconnect',
AppLocalizations.current.disconnectDevices,
cancelNotification: true,
showsUserInterface: false,
),
AndroidNotificationAction(
'close',
AppLocalizations.current.close,
cancelNotification: true,
showsUserInterface: false,
),
],
),
);
_receivePort = ReceivePort();
// If already registered, remove and re-register
IsolateNameServer.removePortNameMapping('_backgroundChannelKey');
final ok = IsolateNameServer.registerPortWithName(_receivePort!.sendPort, '_backgroundChannelKey');
if (!ok) {
// If this happens, something else re-registered immediately or you’re in a weird state.
throw StateError('Failed to register port name');
}
final backgroundMessagePort = _receivePort!.asBroadcastStream();
_sub = backgroundMessagePort.listen((message) {
print('Background isolate received message: $message');
if (message == 'disconnect') {
UniversalBle.onAvailabilityChange = null;
core.connection.disconnectAll();
} else if (message == 'close') {
unawaited(
closeAndQuit().catchError((Object e, StackTrace s) => recordError(e, s, context: 'notification close')),
);
}
//exit(0);
});
}
}
@pragma('vm:entry-point')
void notificationTapBackground(NotificationResponse notificationResponse) {
if (notificationResponse.actionId != null) {
final sendPort = IsolateNameServer.lookupPortByName('_backgroundChannelKey');
sendPort?.send(notificationResponse.actionId);
//exit(0);
}
}