Background location tracking

This commit is contained in:
2026-03-09 22:33:35 +08:00
parent 1e1c7d9552
commit ccc1c62262
10 changed files with 371 additions and 127 deletions
+34 -1
View File
@@ -27,6 +27,39 @@ Future<bool> ensureLocationPermission() async {
final newStatus = await requestLocationPermission();
return newStatus.isGranted;
}
// permanently denied user must open settings
// permanently denied send user to settings so they can enable it
await openAppSettings();
return false;
}
/// Ensures "Allow all the time" (background) location permission is granted.
///
/// This is required for `background_locator_2` to track location when the app
/// is backgrounded or killed. On Android 10+ this triggers the system prompt
/// for `ACCESS_BACKGROUND_LOCATION`. Must be called **after** the foreground
/// location permission (`Permission.location`) has been granted.
Future<bool> ensureBackgroundLocationPermission() async {
if (kIsWeb) return true;
// Foreground location must be granted first; this helper already opens
// settings if the user permanently denied the fine/coarse prompt.
final fgGranted = await ensureLocationPermission();
if (!fgGranted) return false;
final bgStatus = await Permission.locationAlways.status;
if (bgStatus.isGranted) return true;
if (bgStatus.isDenied || bgStatus.isRestricted || bgStatus.isLimited) {
final newStatus = await Permission.locationAlways.request();
if (newStatus.isGranted) return true;
if (newStatus.isPermanentlyDenied) {
// user chose "Don't ask again" send them to settings
await openAppSettings();
}
return false;
}
// Permanently denied user must open settings
await openAppSettings();
return false;
}