Quelltext der von KhorOps geänderten Dateien des Bausteins @capgo/background-geolocation 8.4.14 (Mozilla Public License 2.0, https://mozilla.org/MPL/2.0/) Original: https://github.com/Cap-go/capacitor-background-geolocation Änderung (KhorOps-Patch (29.10.2026)): Antwortet der Server beim Senden eines Standorts mit HTTP 410, beendet der Baustein die Ortung selbst. Alle Änderungen sind mit „KhorOps-Patch“ markiert. Agentur Digitalwerk (KhorOps), Dortmund · info@khorops.de ============================================================================== Datei: android/src/main/java/com/capgo/capacitor_background_geolocation/LocationStore.java ============================================================================== package com.capgo.capacitor_background_geolocation; import android.content.Context; import android.content.SharedPreferences; import com.getcapacitor.Logger; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; // Persists the configuration for a native location watcher and delivers // location updates to a configured URL directly from native code. This mirrors // GeofenceStore and exists so that background location delivery keeps working // after the WebView (and its JavaScript callback) has been destroyed. final class LocationStore { private static final String PREFS_NAME = "CapgoBackgroundGeolocationWatcher"; private static final String KEY_ENABLED = "enabled"; private static final String KEY_URL = "url"; private static final String KEY_TITLE = "title"; private static final String KEY_MESSAGE = "message"; private static final String KEY_DISTANCE_FILTER = "distanceFilter"; private static final String KEY_HEADERS = "headers"; private static final String KEY_MIN_INTERVAL_MS = "minIntervalMs"; private static final String KEY_NETWORK_FALLBACK = "networkFallback"; private static final String KEY_LAST_POST_TIME = "lastPostTime"; private LocationStore() {} // KhorOps-Patch (29.10.2026): Server hat mit 410 geantwortet – Ortung beenden static final class StopRequestedException extends IOException { StopRequestedException() { super("Location POST answered 410 (stop)"); } } private static SharedPreferences prefs(Context context) { return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); } // Persists the watcher config. A null or empty url disables native delivery. static void saveSetup( Context context, String url, String title, String message, float distanceFilter, Map headers, long minIntervalMs, boolean networkFallback ) { SharedPreferences.Editor editor = prefs(context).edit(); if (url == null || url.isEmpty()) { editor.clear(); } else { editor .putBoolean(KEY_ENABLED, true) .putString(KEY_URL, url) .putString(KEY_TITLE, title) .putString(KEY_MESSAGE, message) .putFloat(KEY_DISTANCE_FILTER, distanceFilter) .putString(KEY_HEADERS, headersToJson(headers)) .putLong(KEY_MIN_INTERVAL_MS, Math.max(0L, minIntervalMs)) .putBoolean(KEY_NETWORK_FALLBACK, networkFallback) .remove(KEY_LAST_POST_TIME); } editor.apply(); } static void saveHeaders(Context context, Map headers) { prefs(context).edit().putString(KEY_HEADERS, headersToJson(headers)).apply(); } static void clear(Context context) { prefs(context).edit().clear().apply(); } static boolean isEnabled(Context context) { SharedPreferences prefs = prefs(context); return prefs.getBoolean(KEY_ENABLED, false) && prefs.getString(KEY_URL, null) != null; } static String getUrl(Context context) { return prefs(context).getString(KEY_URL, null); } static String getTitle(Context context) { return prefs(context).getString(KEY_TITLE, "Using your location"); } static String getMessage(Context context) { return prefs(context).getString(KEY_MESSAGE, ""); } static float getDistanceFilter(Context context) { return prefs(context).getFloat(KEY_DISTANCE_FILTER, 0f); } static long getMinIntervalMs(Context context) { return prefs(context).getLong(KEY_MIN_INTERVAL_MS, 0L); } static boolean getNetworkFallback(Context context) { return prefs(context).getBoolean(KEY_NETWORK_FALLBACK, false); } static Map getHeaders(Context context) { return headersFromJson(prefs(context).getString(KEY_HEADERS, null)); } // Returns true when this location should be POSTed given the configured // minimum interval. Points older than the last sent time pass through. static boolean shouldPost(Context context, long locationTimeMs) { long minIntervalMs = getMinIntervalMs(context); if (minIntervalMs <= 0) { return true; } long lastPostTime = prefs(context).getLong(KEY_LAST_POST_TIME, Long.MIN_VALUE); if (lastPostTime != Long.MIN_VALUE && locationTimeMs < lastPostTime) { return true; } if (lastPostTime != Long.MIN_VALUE && locationTimeMs - lastPostTime < minIntervalMs) { return false; } return true; } static void markPosted(Context context, long locationTimeMs) { prefs(context).edit().putLong(KEY_LAST_POST_TIME, locationTimeMs).apply(); } // POSTs a single location as JSON to the configured url. Runs synchronously, // so callers must invoke it off the main thread. static void sendLocation(Context context, JSONObject data) throws IOException { String urlString = getUrl(context); if (urlString == null || urlString.isEmpty()) { return; } long locationTimeMs = data.optLong("time", System.currentTimeMillis()); if (!shouldPost(context, locationTimeMs)) { return; } HttpURLConnection connection = null; try { URL url = new URL(urlString); byte[] body = data.toString().getBytes(StandardCharsets.UTF_8); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setConnectTimeout(15000); connection.setReadTimeout(15000); connection.setDoOutput(true); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Content-Length", String.valueOf(body.length)); for (Map.Entry header : getHeaders(context).entrySet()) { connection.setRequestProperty(header.getKey(), header.getValue()); } try (OutputStream outputStream = connection.getOutputStream()) { outputStream.write(body); } int responseCode = connection.getResponseCode(); Logger.debug("Location POST finished with response code: " + responseCode); // KhorOps-Patch (29.10.2026): HTTP 410 = der Server sagt „Stopp“ (Dienst vorbei, // Zustimmung widerrufen, Firma hat GPS abgeschaltet) if (responseCode == 410) { clear(context); throw new StopRequestedException(); } if (responseCode < HttpURLConnection.HTTP_OK || responseCode >= HttpURLConnection.HTTP_MULT_CHOICE) { throw new IOException("Location POST failed with response code: " + responseCode); } markPosted(context, locationTimeMs); } finally { if (connection != null) { connection.disconnect(); } } } static String headersToJson(Map headers) { JSONObject object = new JSONObject(); if (headers != null) { for (Map.Entry entry : headers.entrySet()) { if (entry.getKey() == null || entry.getValue() == null) { continue; } try { object.put(entry.getKey(), entry.getValue()); } catch (JSONException ignore) {} } } return object.toString(); } static Map headersFromJson(String json) { if (json == null || json.isEmpty()) { return Collections.emptyMap(); } try { JSONObject object = new JSONObject(json); Map headers = new HashMap<>(); Iterator keys = object.keys(); while (keys.hasNext()) { String key = keys.next(); Object value = object.opt(key); if (value != null && value != JSONObject.NULL) { headers.put(key, String.valueOf(value)); } } return headers; } catch (JSONException exception) { Logger.error("Could not parse persisted location headers", exception); return Collections.emptyMap(); } } } ============================================================================== Datei: android/src/main/java/com/capgo/capacitor_background_geolocation/BackgroundGeolocationService.java ============================================================================== package com.capgo.capacitor_background_geolocation; import android.annotation.SuppressLint; import android.app.Notification; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.pm.ServiceInfo; import android.content.res.AssetFileDescriptor; import android.content.res.AssetManager; import android.graphics.Color; import android.location.LocationListener; import android.location.LocationManager; import android.media.MediaPlayer; import android.os.Binder; import android.os.Build; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.PowerManager; import android.os.SystemClock; import androidx.core.app.NotificationCompat; import androidx.core.app.ServiceCompat; import androidx.core.location.LocationCompat; import androidx.core.location.LocationListenerCompat; import com.getcapacitor.Logger; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.json.JSONObject; // A bound and started service that is promoted to a foreground service // (showing a persistent notification) when the first background watcher is // added, and demoted when the last background watcher is removed. public class BackgroundGeolocationService extends Service { static final String NOTIFICATION_CHANNEL_ID = BackgroundGeolocationService.class.getPackage().getName(); private final IBinder binder = new LocalBinder(); private static final double EARTH_RADIUS_M = 6371000; // Must be unique for this application. private static final int NOTIFICATION_ID = 28351; static final String EXTRA_NOTIFICATION_TITLE = "notificationTitle"; static final String EXTRA_NOTIFICATION_MESSAGE = "notificationMessage"; private String callbackId; private LocationManager client; private LocationListener locationCallback; private MediaPlayer mediaPlayer; private double[][] route; private double distanceThreshold; private boolean isOffRoute; private Handler watchdogHandler = new Handler(Looper.getMainLooper()); private Runnable watchdogRunnable; private Runnable restartRunnable; private float currentDistanceFilter; private long currentMinIntervalMs; private PowerManager.WakeLock wakeLock; // How long a GPS fix is considered "fresh" before we allow a NETWORK_PROVIDER fix through. private static final long NETWORK_FALLBACK_GRACE_MS = 20000L; // Max acceptable accuracy radius (meters) for a NETWORK_PROVIDER fix; missing accuracy counts // as too imprecise too. private static final float NETWORK_FIX_MAX_ACCURACY_M = 300f; // elapsedRealtime() of the last GPS_PROVIDER fix, or 0 if none yet. Monotonic, so it can't be // confused by wall-clock adjustments the way System.currentTimeMillis() could. private volatile long lastGpsFixAtMs = 0L; // Opt-in flag for the NETWORK_PROVIDER fallback below; set via the "networkFallback" start // option. Defaults to off, so GPS-only accuracy is unchanged unless a caller asks for it. private volatile boolean networkFallbackEnabled = false; // When set (via the "url" start option), each location is also POSTed to // this URL directly from native code so delivery survives the WebView being // destroyed. Delivery runs on postExecutor to keep it off the main thread. private String nativePostUrl; private ExecutorService postExecutor; @Override public IBinder onBind(Intent intent) { return binder; } // Some devices allow a foreground service to outlive the application's main // activity, leading to nasty crashes as reported in issue #59. If we learn // that the application has been killed, all watchers are stopped and the // service is terminated immediately. // // The exception is native delivery mode (a "url" was given to start()): there // the service is meant to outlive the app UI, so it keeps running and relies // on onStartCommand to re-establish updates if the process is later restarted. @Override public boolean onUnbind(Intent intent) { if (LocationStore.isEnabled(getApplicationContext())) { return false; } if (client != null && locationCallback != null) { client.removeUpdates(locationCallback); } releaseMediaPlayer(); releaseWakeLock(); stopWatchdog(); stopSelf(); return false; } // In native delivery mode, keep tracking after the user swipes the app away // from the recents list; otherwise fall back to the default teardown. @Override public void onTaskRemoved(Intent rootIntent) { if (LocationStore.isEnabled(getApplicationContext())) { return; } super.onTaskRemoved(rootIntent); } // The system may kill and later restart a START_STICKY foreground service // with a null intent and no binder call. When native delivery is configured, // re-establish location updates from the persisted config so tracking resumes // without the app UI. @Override public int onStartCommand(Intent intent, int flags, int startId) { Context context = getApplicationContext(); if (!LocationStore.isEnabled(context)) { // The plugin starts this service with startForegroundService(), and Android // kills the app unless startForeground() follows within a few seconds. Promote // here, so that it does not wait for the bind and the start() call behind it. if (intent != null && intent.hasExtra(EXTRA_NOTIFICATION_TITLE)) { promoteToForeground(intent.getStringExtra(EXTRA_NOTIFICATION_TITLE), intent.getStringExtra(EXTRA_NOTIFICATION_MESSAGE)); } // Not in native delivery mode: preserve the original behavior where the // service does not outlive the app, so it is not sticky-restarted. return START_NOT_STICKY; } nativePostUrl = LocationStore.getUrl(context); promoteToForeground(LocationStore.getTitle(context), LocationStore.getMessage(context)); if (client == null || locationCallback == null) { acquireWakeLock(); client = (LocationManager) getSystemService(Context.LOCATION_SERVICE); currentDistanceFilter = LocationStore.getDistanceFilter(context); currentMinIntervalMs = LocationStore.getMinIntervalMs(context); networkFallbackEnabled = LocationStore.getNetworkFallback(context); locationCallback = createLocationListener(this); lastGpsFixAtMs = SystemClock.elapsedRealtime(); requestLocationUpdates(); startWatchdog(); } return START_STICKY; } @Override public void onDestroy() { if (client != null && locationCallback != null) { client.removeUpdates(locationCallback); } super.onDestroy(); releaseMediaPlayer(); releaseWakeLock(); stopWatchdog(); if (postExecutor != null) { postExecutor.shutdown(); postExecutor = null; } } private void releaseMediaPlayer() { if (mediaPlayer == null) { return; } try { if (mediaPlayer.isPlaying()) { mediaPlayer.stop(); } mediaPlayer.release(); } catch (Exception e) { Logger.error("Error releasing MediaPlayer", e); } mediaPlayer = null; } // No timeout: tracking runs for as long as the caller keeps a background watcher // registered, and the lock is always released in stop() and onDestroy(). @SuppressLint("WakelockTimeout") private void acquireWakeLock() { if (wakeLock != null && wakeLock.isHeld()) { return; } try { PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "BackgroundGeolocation::LocationWakeLock"); wakeLock.acquire(); Logger.info("Wake lock acquired"); } catch (Exception e) { Logger.error("Error acquiring wake lock", e); } } private void releaseWakeLock() { if (wakeLock == null) { return; } try { if (wakeLock.isHeld()) { wakeLock.release(); Logger.info("Wake lock released"); } } catch (Exception e) { Logger.error("Error releasing wake lock", e); } wakeLock = null; } private void restartLocationUpdates() { Logger.debug("Location watchdog timed out, restarting updates"); if (client == null || locationCallback == null) { return; } client.removeUpdates(locationCallback); if (restartRunnable != null) { watchdogHandler.removeCallbacks(restartRunnable); } restartRunnable = () -> { if (client == null || locationCallback == null) { return; } requestLocationUpdates(); startWatchdog(); }; watchdogHandler.postDelayed(restartRunnable, 10000); } private void startWatchdog() { stopWatchdog(); if (watchdogRunnable == null) { watchdogRunnable = this::restartLocationUpdates; } watchdogHandler.postDelayed(watchdogRunnable, 60000); } private void stopWatchdog() { if (watchdogRunnable != null) { watchdogHandler.removeCallbacks(watchdogRunnable); } if (restartRunnable != null) { watchdogHandler.removeCallbacks(restartRunnable); } } private void handleLocationChanged(android.location.Location location) { if (LocationManager.GPS_PROVIDER.equals(location.getProvider())) { lastGpsFixAtMs = SystemClock.elapsedRealtime(); } else if (LocationManager.NETWORK_PROVIDER.equals(location.getProvider())) { boolean gpsStillFresh = lastGpsFixAtMs != 0 && SystemClock.elapsedRealtime() - lastGpsFixAtMs < NETWORK_FALLBACK_GRACE_MS; boolean tooImprecise = !location.hasAccuracy() || location.getAccuracy() > NETWORK_FIX_MAX_ACCURACY_M; if (gpsStillFresh || tooImprecise) { // Drop it - and skip startWatchdog() below so a run of rejected fixes can't mask a // genuinely stalled GPS_PROVIDER and suppress the restart that would recover it. return; } } startWatchdog(); if (nativePostUrl != null) { postLocationNatively(location); } if (mediaPlayer != null) { double[] point = { location.getLongitude(), location.getLatitude() }; var offRoute = distancePointToRoute(point) > distanceThreshold; if (offRoute == true && isOffRoute == false) { mediaPlayer.start(); } isOffRoute = offRoute; } LocalEvents.emitLocation(callbackId, location); } // Delivers a location to the configured URL from native code, so it works // even when the WebView/JavaScript layer no longer exists. private void postLocationNatively(android.location.Location location) { if (postExecutor == null) { postExecutor = Executors.newSingleThreadExecutor(); } Context context = getApplicationContext(); JSONObject payload = locationToJson(location); postExecutor.execute(() -> { try { LocationStore.sendLocation(context, payload); } catch (LocationStore.StopRequestedException stop) { // KhorOps-Patch (29.10.2026): Server sagt „Stopp“ → Dienst selbst beenden, // auch wenn die App weggewischt ist (kein JavaScript) new android.os.Handler(android.os.Looper.getMainLooper()).post(this::stopFromServer); } catch (Exception e) { Logger.error("Native location POST failed", e); } }); } // KhorOps-Patch (29.10.2026): wie LocalBinder.stop(), aber vom Server ausgelöst private void stopFromServer() { LocationStore.clear(getApplicationContext()); nativePostUrl = null; stopWatchdog(); if (client != null && locationCallback != null) { client.removeUpdates(locationCallback); } ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE); stopSelf(); releaseMediaPlayer(); releaseWakeLock(); } private static JSONObject locationToJson(android.location.Location location) { JSONObject obj = new JSONObject(); try { obj.put("latitude", location.getLatitude()); obj.put("longitude", location.getLongitude()); obj.put("accuracy", location.hasAccuracy() ? location.getAccuracy() : JSONObject.NULL); obj.put("altitude", location.hasAltitude() ? location.getAltitude() : JSONObject.NULL); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && location.hasVerticalAccuracy()) { obj.put("altitudeAccuracy", location.getVerticalAccuracyMeters()); } else { obj.put("altitudeAccuracy", JSONObject.NULL); } obj.put("simulated", LocationCompat.isMock(location)); obj.put("speed", location.hasSpeed() ? location.getSpeed() : JSONObject.NULL); obj.put("bearing", location.hasBearing() ? location.getBearing() : JSONObject.NULL); obj.put("time", location.getTime()); // Lets the server distinguish native-delivered updates from those // forwarded by the JavaScript callback. obj.put("source", "native"); } catch (org.json.JSONException e) { Logger.error("Could not serialize location", e); } return obj; } // Android API < 30 static LocationListenerCompat createLocationListener(final BackgroundGeolocationService service) { return (location) -> service.handleLocationChanged(location); } private long locationIntervalMs() { return currentMinIntervalMs > 0 ? currentMinIntervalMs : 1000L; } private void requestLocationUpdates() { try { client.requestLocationUpdates(LocationManager.GPS_PROVIDER, locationIntervalMs(), currentDistanceFilter, locationCallback); } catch (SecurityException ignore) { // According to Android Studio, this method can throw a Security Exception if // permissions are not yet granted. Rather than check the permissions, which is fiddly, // we simply ignore the exception. } if (!networkFallbackEnabled) { return; } // GPS_PROVIDER can go quiet for extended periods in the background or with poor sky // visibility. Request NETWORK_PROVIDER on the same listener as a fallback; whichever // fires first reaches handleLocationChanged(). No manifest change needed - // ACCESS_COARSE_LOCATION is already declared. isProviderEnabled guards against devices // with network location turned off. try { if (client.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { client.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, locationIntervalMs(), currentDistanceFilter, locationCallback ); } } catch (SecurityException ignore) { // Same rationale as the GPS_PROVIDER catch above. } } // Promote the service to the foreground if necessary. // Ideally we would only call 'startForeground' if the service is not already // foregrounded. Unfortunately, 'getForegroundServiceType' was only introduced // in API level 29 and seems to behave weirdly, as reported in #120. However, // it appears that 'startForeground' is idempotent, so we just call it repeatedly // each time a background watcher is added. private void promoteToForeground(String notificationTitle, String notificationMessage) { try { // This method has been known to fail due to weird // permission bugs, so we prevent any exceptions from // crashing the app. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { startForeground( NOTIFICATION_ID, createBackgroundNotification(notificationTitle, notificationMessage), ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION ); } else { startForeground(NOTIFICATION_ID, createBackgroundNotification(notificationTitle, notificationMessage)); } } catch (Exception exception) { Logger.error("Failed to foreground service", exception); } } // Handles requests from the activity. public class LocalBinder extends Binder { void start( final String id, final String notificationTitle, final String notificationMessage, float distanceFilter, final String url, final Map headers, final long minIntervalMs, final boolean networkFallback ) { // The plugin starts this service with startForegroundService(). If the setup // below throws (for example 'provider "gps" does not exist' on a device without // a GPS chip), the plugin stops the service again, and Android kills the app // unless startForeground() already ran. So promote first. promoteToForeground(notificationTitle, notificationMessage); releaseMediaPlayer(); acquireWakeLock(); client = (LocationManager) getSystemService(Context.LOCATION_SERVICE); lastGpsFixAtMs = SystemClock.elapsedRealtime(); callbackId = id; currentDistanceFilter = distanceFilter; currentMinIntervalMs = Math.max(0L, minIntervalMs); networkFallbackEnabled = networkFallback; nativePostUrl = url == null || url.isEmpty() ? null : url; LocationStore.saveSetup( getApplicationContext(), nativePostUrl, notificationTitle, notificationMessage, distanceFilter, headers, currentMinIntervalMs, networkFallback ); // The service may already be running (for example after a sticky // restart), so drop any previous listener before registering a new one. if (locationCallback != null) { client.removeUpdates(locationCallback); } locationCallback = createLocationListener(BackgroundGeolocationService.this); requestLocationUpdates(); // Arm the watchdog here so rejected network fixes during the grace period cannot // leave tracking without a restart path if GPS_PROVIDER goes silent. startWatchdog(); } void updateHeaders(final Map headers) { LocationStore.saveHeaders(getApplicationContext(), headers); } String stop() { LocationStore.clear(getApplicationContext()); nativePostUrl = null; stopWatchdog(); // stop() can reach a bound service whose start() has not run yet // (JS calls start() then stop() back-to-back), in which case neither // field is set. Same guard as onUnbind() and onDestroy(). if (client != null && locationCallback != null) { client.removeUpdates(locationCallback); } ServiceCompat.stopForeground(BackgroundGeolocationService.this, ServiceCompat.STOP_FOREGROUND_REMOVE); stopSelf(); releaseMediaPlayer(); releaseWakeLock(); return callbackId; } void setPlannedRoute(String filePath, double[][] routeCoordinates, float distance) { route = routeCoordinates; distanceThreshold = distance; isOffRoute = true; try { if (mediaPlayer != null) { return; } mediaPlayer = new MediaPlayer(); AssetManager am = getApplicationContext().getResources().getAssets(); AssetFileDescriptor assetFileDescriptor = am.openFd("public/" + filePath); mediaPlayer.setDataSource( assetFileDescriptor.getFileDescriptor(), assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength() ); mediaPlayer.setLooping(false); mediaPlayer.setOnErrorListener((mp, what, extra) -> { Logger.error("MediaPlayer error: what=" + what + ", extra=" + extra); releaseMediaPlayer(); return true; // Indicate we handled the error }); mediaPlayer.prepareAsync(); } catch (Exception e) { Logger.error("PlaySound: Unexpected error", e); releaseMediaPlayer(); } } } private Notification createBackgroundNotification(String backgroundTitle, String backgroundMessage) { NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), NOTIFICATION_CHANNEL_ID) .setContentTitle(backgroundTitle) .setContentText(backgroundMessage) .setOngoing(true) .setPriority(NotificationCompat.PRIORITY_HIGH) .setWhen(System.currentTimeMillis()); try { String name = getAppString("capacitor_background_geolocation_notification_icon", "mipmap/ic_launcher", getApplicationContext()); String[] parts = name.split("/"); // It is actually necessary to set a valid icon for the notification to behave // correctly when tapped. If there is no icon specified, tapping it will open the // app's settings, rather than bringing the application to the foreground. builder.setSmallIcon(getAppResourceIdentifier(parts[1], parts[0], getApplicationContext())); } catch (Exception e) { Logger.error("Could not set notification icon", e); } try { String color = getAppString("capacitor_background_geolocation_notification_color", null, getApplicationContext()); if (color != null) { builder.setColor(Color.parseColor(color)); } } catch (Exception e) { Logger.error("Could not set notification color", e); } Intent launchIntent = getApplicationContext() .getPackageManager() .getLaunchIntentForPackage(getApplicationContext().getPackageName()); if (launchIntent != null) { launchIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); builder.setContentIntent( PendingIntent.getActivity( getApplicationContext(), 0, launchIntent, PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE ) ); } return builder.build(); } // Gets the identifier of the app's resource by name, returning 0 if not found. // The name comes from the host app's configuration, so it can only be resolved by // reflection; the compile-time R class of this library does not contain it. @SuppressLint("DiscouragedApi") private static int getAppResourceIdentifier(String name, String defType, Context context) { return context.getResources().getIdentifier(name, defType, context.getPackageName()); } // Gets a string from the app's strings.xml file, resorting to a fallback if it is not defined. public static String getAppString(String name, String fallback, Context context) { int id = getAppResourceIdentifier(name, "string", context); return id == 0 ? fallback : context.getString(id); } private static double haversine(double[] point1, double[] point2) { double lon1 = point1[0]; double lat1 = point1[1]; double lon2 = point2[0]; double lat2 = point2[1]; double dLat = Math.toRadians(lat2 - lat1); double dLon = Math.toRadians(lon2 - lon1); double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2); double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return EARTH_RADIUS_M * c; } private static double distancePointToLineSegment(double[] point, double[] lineStart, double[] lineEnd) { // Calculate the distances between the three points using Haversine double dist_A_B = haversine(point, lineStart); double dist_A_C = haversine(point, lineEnd); double dist_B_C = haversine(lineStart, lineEnd); // Handle the edge case where the line segment is a single point if (dist_B_C == 0) { return dist_A_B; } // Check if the angles at the line segment's endpoints are obtuse. // We use the Law of Cosines (c^2 = a^2 + b^2 - 2ab*cos(C)) // If cos(C) < 0, the angle is obtuse. // Angle at B (lineStart) // Use a small epsilon to handle floating point inaccuracies in division by zero double cos_B = (Math.pow(dist_A_B, 2) + Math.pow(dist_B_C, 2) - Math.pow(dist_A_C, 2)) / (2 * dist_A_B * dist_B_C); if (cos_B < 0) { return dist_A_B; } // Angle at C (lineEnd) double cos_C = (Math.pow(dist_A_C, 2) + Math.pow(dist_B_C, 2) - Math.pow(dist_A_B, 2)) / (2 * dist_A_C * dist_B_C); if (cos_C < 0) { return dist_A_C; } // If both angles are acute, the closest point is on the line segment itself. // We can calculate the distance (height of the triangle) using its area. // 1. Calculate the semi-perimeter of the triangle ABC double s = (dist_A_B + dist_A_C + dist_B_C) / 2; // 2. Calculate the area using Heron's formula double area = Math.sqrt(Math.max(0, s * (s - dist_A_B) * (s - dist_A_C) * (s - dist_B_C))); // 3. The distance is the height of the triangle from point A to the base BC // Area = 0.5 * base * height => height = 2 * Area / base return (2 * area) / dist_B_C; } public double distancePointToRoute(double[] point) { // If the polyline has less than 2 points, we can't form a segment. if (this.route.length < 2) { if (this.route.length == 1) { return haversine(point, this.route[0]); } return Double.POSITIVE_INFINITY; // No line segments to measure against } double minDistance = Double.POSITIVE_INFINITY; for (int i = 0; i < this.route.length - 1; i++) { double[] lineStart = this.route[i]; double[] lineEnd = this.route[i + 1]; double distance = distancePointToLineSegment(point, lineStart, lineEnd); if (distance < minDistance) { minDistance = distance; } } return minDistance; } } ============================================================================== Datei: ios/Sources/CapgoBackgroundGeolocationPlugin/CapgoCapacitorBackgroundGeolocationPlugin.swift ============================================================================== // swiftlint:disable file_length import Capacitor import Foundation import UIKit import CoreLocation import AVFoundation // Avoids a bewildering type warning. let null = Optional.none as Any func formatLocation(_ location: CLLocation) -> PluginCallResultData { var simulated = false if #available(iOS 15, *) { // Prior to iOS 15, it was not possible to detect simulated locations. // But in general, it is very difficult to simulate locations on iOS in // production. if let sourceInfo = location.sourceInformation { simulated = sourceInfo.isSimulatedBySoftware } } return [ "latitude": location.coordinate.latitude, "longitude": location.coordinate.longitude, "accuracy": location.horizontalAccuracy, "altitude": location.altitude, "altitudeAccuracy": location.verticalAccuracy, "simulated": simulated, "speed": location.speed < 0 ? null : location.speed, "bearing": location.course < 0 ? null : location.course, "time": NSNumber( value: Int( location.timestamp.timeIntervalSince1970 * 1000 ) ) ] } @objc(BackgroundGeolocation) // swiftlint:disable:next type_body_length public class BackgroundGeolocation: CAPPlugin, CLLocationManagerDelegate, CAPBridgedPlugin { private let pluginVersion: String = "8.4.14" public let identifier = "BackgroundGeolocationPlugin" public let jsName = "BackgroundGeolocation" public let pluginMethods: [CAPPluginMethod] = [ CAPPluginMethod(name: "start", returnType: CAPPluginReturnCallback), CAPPluginMethod(name: "stop", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "openSettings", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "setPlannedRoute", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "setupGeofencing", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "addGeofence", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "removeGeofence", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "removeAllGeofences", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "getMonitoredGeofences", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "checkPermissions", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "requestPermissions", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "updateHeaders", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "getPluginVersion", returnType: CAPPluginReturnPromise) ] private var locationManager: CLLocationManager? private var geofenceLocationManager: CLLocationManager? private var created: Date? private var allowStale: Bool = false private var isUpdatingLocation: Bool = false private var activeCallbackId: String? private var audioPlayer: AVAudioPlayer? private var plannedRoute: [[Double]] = [] private var isOffRoute: Bool = true private var distanceThreshold: Double = 50.0 // Default distance threshold in meters private var geofenceBackendUrl: URL? private var geofenceNotifyOnEntry: Bool = true private var geofenceNotifyOnExit: Bool = true private var geofencePayload: [String: Any] = [:] private var pendingGeofenceSetupCall: CAPPluginCall? private var pendingGeofenceSetupTimeout: DispatchWorkItem? private var pendingPermissionRequestCall: CAPPluginCall? private var pendingPermissionRequestTimeout: DispatchWorkItem? private var pendingGeofenceAddCalls: [String: CAPPluginCall] = [:] private var pendingGeofenceRegions: [String: (region: CLCircularRegion, payload: [String: Any])] = [:] private var lastGeofenceTransition: [String: String] = [:] // When set (via the "url" start option), each valid location is also POSTed // as JSON directly from native code, independently of the WebView. private var locationBackendUrl: URL? private var locationHeaders: [String: String] = [:] private var geofenceHeaders: [String: String] = [:] private var minIntervalMs: Double = 0 private var lastPostedLocationTime: Date? private let geofenceUrlKey = "CapgoBackgroundGeolocation.geofence.url" private let geofenceHeadersKey = "CapgoBackgroundGeolocation.geofence.headers" private let geofenceNotifyOnEntryKey = "CapgoBackgroundGeolocation.geofence.notifyOnEntry" private let geofenceNotifyOnExitKey = "CapgoBackgroundGeolocation.geofence.notifyOnExit" private let geofencePayloadKey = "CapgoBackgroundGeolocation.geofence.payload" private let geofenceRegionPrefix = "CapgoBackgroundGeolocation.geofence.region." // Earth radius in meters for distance calculations private static let earthRadiusMeters: Double = 6371000.0 @objc override public func load() { UIDevice.current.isBatteryMonitoringEnabled = true restoreGeofenceConfiguration() DispatchQueue.main.async { _ = self.ensureGeofenceLocationManager() } } @objc func start(_ call: CAPPluginCall) { call.keepAlive = true // CLLocationManager requires main thread DispatchQueue.main.async { // Check if already started if self.locationManager != nil { return call.reject("Location tracking already started", "ALREADY_STARTED") } // Optional native delivery endpoint (same validation as setupGeofencing). if let urlString = call.getString("url"), !urlString.isEmpty { guard let url = URL(string: urlString), let scheme = url.scheme?.lowercased(), ["http", "https"].contains(scheme) else { return call.reject("Given url is not valid") } self.locationBackendUrl = url } else { self.locationBackendUrl = nil } self.locationHeaders = self.stringHeaders(from: call.getObject("headers")) self.minIntervalMs = max(0, call.getDouble("minIntervalMs") ?? 0) self.lastPostedLocationTime = nil // Create fresh location manager and initialize date self.locationManager = CLLocationManager() guard let manager = self.locationManager else { return call.reject("Failed to create location manager") } manager.delegate = self self.created = Date() let background = call.getString("backgroundMessage") != nil self.allowStale = call.getBool("stale") ?? false self.activeCallbackId = call.callbackId self.configureLocationManager(manager, call: call, background: background) if call.getBool("requestPermissions") != false { if self.handlePermissions(manager, background: background) { return } } return self.startUpdatingLocation() } } private func configureLocationManager(_ manager: CLLocationManager, call: CAPPluginCall, background: Bool) { let externalPower = [ .full, .charging ].contains(UIDevice.current.batteryState) manager.desiredAccuracy = ( externalPower ? kCLLocationAccuracyBestForNavigation : kCLLocationAccuracyBest ) var distanceFilter = call.getDouble("distanceFilter") // It appears that setting manager.distanceFilter to 0 can prevent // subsequent location updates. See issue #88. if distanceFilter == nil || distanceFilter == 0 { distanceFilter = kCLDistanceFilterNone } manager.distanceFilter = distanceFilter ?? kCLDistanceFilterNone manager.allowsBackgroundLocationUpdates = background manager.showsBackgroundLocationIndicator = background manager.pausesLocationUpdatesAutomatically = false } private func handlePermissions(_ manager: CLLocationManager, background: Bool) -> Bool { let status = manager.authorizationStatus if [ .notDetermined, .denied, .restricted ].contains(status) { if background { manager.requestAlwaysAuthorization() } else { manager.requestWhenInUseAuthorization() } return true } if background && status == .authorizedWhenInUse { // Attempt to escalate. manager.requestAlwaysAuthorization() } return false } @objc func stop(_ call: CAPPluginCall) { // CLLocationManager requires main thread DispatchQueue.main.async { self.stopUpdatingLocation() self.locationManager?.delegate = nil self.locationManager = nil self.created = nil self.locationBackendUrl = nil self.locationHeaders = [:] self.minIntervalMs = 0 self.lastPostedLocationTime = nil if let callbackId = self.activeCallbackId { if let savedCall = self.bridge?.savedCall(withID: callbackId) { savedCall.keepAlive = false } self.activeCallbackId = nil } return call.resolve() } } @objc func updateHeaders(_ call: CAPPluginCall) { DispatchQueue.main.async { let headers = self.stringHeaders(from: call.getObject("headers")) self.locationHeaders = headers self.geofenceHeaders = headers self.persistGeofenceConfiguration() call.resolve() } } @objc func openSettings(_ call: CAPPluginCall) { DispatchQueue.main.async { guard let settingsUrl = URL( string: UIApplication.openSettingsURLString ) else { return call.reject("No link to settings available") } if UIApplication.shared.canOpenURL(settingsUrl) { UIApplication.shared.open(settingsUrl, completionHandler: { (success) in if success { return call.resolve() } else { return call.reject("Failed to open settings") } }) } else { return call.reject("Cannot open settings") } } } @objc func setPlannedRoute(_ call: CAPPluginCall) { DispatchQueue.global(qos: .background).async { [weak self] in guard let self = self else { return } guard let soundFile = call.getString("soundFile") else { call.reject("Sound file is required") return } let routeArray = call.getArray("route", Any.self) ?? [] var route: [[Double]] = [] for routePoint in routeArray { if let pointArray = routePoint as? [Double], pointArray.count == 2 { route.append(pointArray) } } let distance = call.getDouble("distance") ?? 50.0 let assetPath = "public/" + soundFile let assetPathSplit = assetPath.components(separatedBy: ".") guard let url = Bundle.main.url(forResource: assetPathSplit[0], withExtension: assetPathSplit[1]) else { call.reject("Sound file not found: \(assetPath)") return } do { self.audioPlayer?.stop() self.audioPlayer = nil self.audioPlayer = try AVAudioPlayer(contentsOf: url) // Store route configuration self.plannedRoute = route self.distanceThreshold = distance self.isOffRoute = true call.resolve() } catch { call.reject("Could not load the sound file: \(error.localizedDescription)") } } } private func requestGeofenceAlwaysAuthorization(_ call: CAPPluginCall, manager: CLLocationManager, status: CLAuthorizationStatus) { pendingGeofenceSetupCall = call pendingGeofenceSetupTimeout?.cancel() let timeout = DispatchWorkItem { [weak self] in guard let self = self, let pendingCall = self.pendingGeofenceSetupCall else { return } self.pendingGeofenceSetupCall = nil self.pendingGeofenceSetupTimeout = nil if manager.authorizationStatus == .authorizedAlways { pendingCall.resolve() } else { pendingCall.reject( "Always location permission is required for geofencing", "NOT_AUTHORIZED" ) } } pendingGeofenceSetupTimeout = timeout manager.requestAlwaysAuthorization() if status == .authorizedWhenInUse { DispatchQueue.main.asyncAfter(deadline: .now() + 30, execute: timeout) } } @objc func setupGeofencing(_ call: CAPPluginCall) { DispatchQueue.main.async { if self.pendingGeofenceSetupCall != nil { return call.reject("A geofence permission request is already in progress", "PERMISSION_REQUEST_IN_PROGRESS") } guard CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) else { return call.reject("Geofencing is not available on this device", "NOT_AVAILABLE") } var backendUrl: URL? if let urlString = call.getString("url"), !urlString.isEmpty { guard let url = URL(string: urlString), let scheme = url.scheme?.lowercased(), ["http", "https"].contains(scheme) else { return call.reject("Given url is not valid") } backendUrl = url } let payload = call.getObject("payload") ?? [:] guard JSONSerialization.isValidJSONObject(payload) else { return call.reject("Payload must be valid JSON") } self.geofenceBackendUrl = backendUrl self.geofenceHeaders = self.stringHeaders(from: call.getObject("headers")) self.geofenceNotifyOnEntry = call.getBool("notifyOnEntry") ?? true self.geofenceNotifyOnExit = call.getBool("notifyOnExit") ?? true self.geofencePayload = payload self.persistGeofenceConfiguration() let manager = self.ensureGeofenceLocationManager() let status = manager.authorizationStatus if status == .authorizedAlways { return call.resolve() } if call.getBool("requestPermissions") == false { return call.reject("Always location permission is required for geofencing", "NOT_AUTHORIZED") } if [.denied, .restricted].contains(status) { return call.reject("Always location permission is required for geofencing", "NOT_AUTHORIZED") } self.requestGeofenceAlwaysAuthorization(call, manager: manager, status: status) } } @objc func addGeofence(_ call: CAPPluginCall) { DispatchQueue.main.async { let manager = self.ensureGeofenceLocationManager() guard self.geofenceAvailable(manager) else { return call.reject("Always location permission is required for geofencing", "NOT_AUTHORIZED") } guard let latitude = call.getDouble("latitude") else { return call.reject("Latitude is required") } guard let longitude = call.getDouble("longitude") else { return call.reject("Longitude is required") } guard let identifier = call.getString("identifier"), !identifier.isEmpty else { return call.reject("Identifier is required") } let radius = call.getDouble("radius") ?? 50.0 guard CLLocationCoordinate2DIsValid(CLLocationCoordinate2D(latitude: latitude, longitude: longitude)) else { return call.reject("Invalid latitude or longitude") } guard radius > 0 else { return call.reject("Radius must be greater than 0") } let maximumDistance = manager.maximumRegionMonitoringDistance guard maximumDistance <= 0 || radius <= maximumDistance else { return call.reject("Radius exceeds the maximum supported region monitoring distance") } let notifyOnEntry = call.getBool("notifyOnEntry") ?? self.geofenceNotifyOnEntry let notifyOnExit = call.getBool("notifyOnExit") ?? self.geofenceNotifyOnExit guard notifyOnEntry || notifyOnExit else { return call.reject("At least one transition must be enabled") } let payload = call.getObject("payload") ?? [:] guard JSONSerialization.isValidJSONObject(payload) else { return call.reject("Payload must be valid JSON") } guard self.pendingGeofenceAddCalls[identifier] == nil else { return call.reject("A geofence with that identifier is already being added", "PENDING") } let center = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) let region = CLCircularRegion(center: center, radius: radius, identifier: identifier) region.notifyOnEntry = notifyOnEntry region.notifyOnExit = notifyOnExit self.pendingGeofenceAddCalls[identifier] = call self.pendingGeofenceRegions[identifier] = (region, payload) manager.startMonitoring(for: region) } } @objc func removeGeofence(_ call: CAPPluginCall) { DispatchQueue.main.async { guard let identifier = call.getString("identifier"), !identifier.isEmpty else { return call.reject("Identifier is required") } let manager = self.ensureGeofenceLocationManager() if let pending = self.pendingGeofenceRegions.removeValue(forKey: identifier) { manager.stopMonitoring(for: pending.region) self.pendingGeofenceAddCalls.removeValue(forKey: identifier)?.reject( "Geofence was removed before monitoring started", "CANCELLED" ) self.removePersistedGeofenceRegion(identifier) self.lastGeofenceTransition.removeValue(forKey: identifier) return call.resolve() } guard self.persistedGeofenceRegionIds().contains(identifier) else { return call.reject("Could not find a region with that identifier", "NOT_FOUND") } guard let region = manager.monitoredRegions.first(where: { $0.identifier == identifier && $0 is CLCircularRegion }) else { self.pendingGeofenceAddCalls.removeValue(forKey: identifier)?.reject("Geofence was removed before monitoring started", "CANCELLED") self.pendingGeofenceRegions.removeValue(forKey: identifier) self.removePersistedGeofenceRegion(identifier) self.lastGeofenceTransition.removeValue(forKey: identifier) return call.resolve() } manager.stopMonitoring(for: region) self.pendingGeofenceAddCalls.removeValue(forKey: identifier)?.reject("Geofence was removed before monitoring started", "CANCELLED") self.pendingGeofenceRegions.removeValue(forKey: identifier) self.removePersistedGeofenceRegion(identifier) self.lastGeofenceTransition.removeValue(forKey: identifier) call.resolve() } } @objc func removeAllGeofences(_ call: CAPPluginCall) { DispatchQueue.main.async { let manager = self.ensureGeofenceLocationManager() let identifiers = self.persistedGeofenceRegionIds() for region in manager.monitoredRegions where region is CLCircularRegion && identifiers.contains(region.identifier) { manager.stopMonitoring(for: region) } for identifier in identifiers { self.removePersistedGeofenceRegion(identifier) self.lastGeofenceTransition.removeValue(forKey: identifier) } for (_, pendingCall) in self.pendingGeofenceAddCalls { pendingCall.reject("Geofences were removed before monitoring started", "CANCELLED") } self.pendingGeofenceAddCalls.removeAll() self.pendingGeofenceRegions.removeAll() call.resolve() } } @objc func getMonitoredGeofences(_ call: CAPPluginCall) { DispatchQueue.main.async { let manager = self.ensureGeofenceLocationManager() let identifiers = self.persistedGeofenceRegionIds() let regions = manager.monitoredRegions.compactMap { region -> String? in region is CLCircularRegion && identifiers.contains(region.identifier) ? region.identifier : nil }.sorted() call.resolve(["regions": regions]) } } private func ensureGeofenceLocationManager() -> CLLocationManager { if let manager = geofenceLocationManager { return manager } let manager = CLLocationManager() manager.delegate = self manager.pausesLocationUpdatesAutomatically = false geofenceLocationManager = manager return manager } private func geofenceAvailable(_ manager: CLLocationManager) -> Bool { CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) && manager.authorizationStatus == .authorizedAlways } private func persistGeofenceConfiguration() { let defaults = UserDefaults.standard defaults.set(geofenceBackendUrl?.absoluteString, forKey: geofenceUrlKey) defaults.set(geofenceNotifyOnEntry, forKey: geofenceNotifyOnEntryKey) defaults.set(geofenceNotifyOnExit, forKey: geofenceNotifyOnExitKey) if JSONSerialization.isValidJSONObject(geofencePayload), let data = try? JSONSerialization.data(withJSONObject: geofencePayload) { defaults.set(data, forKey: geofencePayloadKey) } else { defaults.removeObject(forKey: geofencePayloadKey) } if JSONSerialization.isValidJSONObject(geofenceHeaders), let data = try? JSONSerialization.data(withJSONObject: geofenceHeaders) { defaults.set(data, forKey: geofenceHeadersKey) } else { defaults.removeObject(forKey: geofenceHeadersKey) } } private func restoreGeofenceConfiguration() { let defaults = UserDefaults.standard if let urlString = defaults.string(forKey: geofenceUrlKey), !urlString.isEmpty { geofenceBackendUrl = URL(string: urlString) } if defaults.object(forKey: geofenceNotifyOnEntryKey) != nil { geofenceNotifyOnEntry = defaults.bool(forKey: geofenceNotifyOnEntryKey) } if defaults.object(forKey: geofenceNotifyOnExitKey) != nil { geofenceNotifyOnExit = defaults.bool(forKey: geofenceNotifyOnExitKey) } if let data = defaults.data(forKey: geofencePayloadKey), let payload = try? JSONSerialization.jsonObject(with: data) as? [String: Any] { geofencePayload = payload } if let data = defaults.data(forKey: geofenceHeadersKey), let headers = try? JSONSerialization.jsonObject(with: data) as? [String: Any] { geofenceHeaders = stringHeaders(from: headers) } } private func persistGeofenceRegion(_ region: CLCircularRegion, payload: [String: Any]) { let data: [String: Any] = [ "latitude": region.center.latitude, "longitude": region.center.longitude, "radius": region.radius, "payload": payload ] if JSONSerialization.isValidJSONObject(data), let encoded = try? JSONSerialization.data(withJSONObject: data) { UserDefaults.standard.set(encoded, forKey: geofenceRegionPrefix + region.identifier) } } private func persistedGeofenceRegion(_ identifier: String) -> [String: Any] { guard let data = UserDefaults.standard.data(forKey: geofenceRegionPrefix + identifier), let decoded = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return [:] } return decoded } private func removePersistedGeofenceRegion(_ identifier: String) { UserDefaults.standard.removeObject(forKey: geofenceRegionPrefix + identifier) } private func persistedGeofenceRegionIds() -> Set { Set(UserDefaults.standard.dictionaryRepresentation().keys.compactMap { key in guard key.hasPrefix(geofenceRegionPrefix) else { return nil } return String(key.dropFirst(geofenceRegionPrefix.count)) }) } private func geofenceTransitionData(for region: CLRegion, enter: Bool) -> [String: Any] { let persistedRegion = persistedGeofenceRegion(region.identifier) let regionPayload = persistedRegion["payload"] as? [String: Any] ?? [:] var payload = geofencePayload for (key, value) in regionPayload { payload[key] = value } var data = payload data["identifier"] = region.identifier data["transition"] = enter ? "enter" : "exit" data["enter"] = enter if let circularRegion = region as? CLCircularRegion { data["latitude"] = circularRegion.center.latitude data["longitude"] = circularRegion.center.longitude data["radius"] = circularRegion.radius } else { data["latitude"] = persistedRegion["latitude"] data["longitude"] = persistedRegion["longitude"] data["radius"] = persistedRegion["radius"] } data["payload"] = payload return data } private func handleGeofenceTransition(for region: CLRegion, enter: Bool) { if let circularRegion = region as? CLCircularRegion { if enter && !circularRegion.notifyOnEntry { return } if !enter && !circularRegion.notifyOnExit { return } } let transition = enter ? "enter" : "exit" if lastGeofenceTransition[region.identifier] == transition { return } lastGeofenceTransition[region.identifier] = transition let data = geofenceTransitionData(for: region, enter: enter) notifyListeners("geofenceTransition", data: data, retainUntilConsumed: true) postGeofenceTransition(data) } private func postGeofenceTransition(_ data: [String: Any]) { guard let backendUrl = geofenceBackendUrl, JSONSerialization.isValidJSONObject(data), let body = try? JSONSerialization.data(withJSONObject: data) else { return } postJson(body, to: backendUrl, headers: geofenceHeaders, taskName: "CapgoGeofenceTransition") } // Like formatLocation, but safe for JSONSerialization: the bridge's // optional-based null sentinel cannot be serialized, so missing values are // encoded as NSNull instead. Includes "source": "native" so the server can // distinguish native POSTs from updates forwarded by the JavaScript layer. private func locationPayload(_ location: CLLocation) -> [String: Any] { var simulated = false if #available(iOS 15, *) { if let sourceInfo = location.sourceInformation { simulated = sourceInfo.isSimulatedBySoftware } } var data: [String: Any] = [ "latitude": location.coordinate.latitude, "longitude": location.coordinate.longitude, "accuracy": location.horizontalAccuracy, "altitude": location.altitude, "altitudeAccuracy": location.verticalAccuracy, "simulated": simulated, "time": NSNumber( value: Int( location.timestamp.timeIntervalSince1970 * 1000 ) ), "source": "native" ] if location.speed < 0 { data["speed"] = NSNull() } else { data["speed"] = location.speed } if location.course < 0 { data["bearing"] = NSNull() } else { data["bearing"] = location.course } return data } // Delivers a location to the configured URL from native code, in parallel // with (and independently of) the JavaScript callback. private func shouldPostLocation(_ location: CLLocation) -> Bool { guard minIntervalMs > 0 else { return true } guard let lastPostedLocationTime else { return true } if location.timestamp < lastPostedLocationTime { return true } let elapsedMs = location.timestamp.timeIntervalSince(lastPostedLocationTime) * 1000 return elapsedMs >= minIntervalMs } private func postLocation(_ location: CLLocation) { guard let backendUrl = locationBackendUrl else { return } guard shouldPostLocation(location) else { return } let data = locationPayload(location) guard JSONSerialization.isValidJSONObject(data), let body = try? JSONSerialization.data(withJSONObject: data) else { return } lastPostedLocationTime = location.timestamp postJson(body, to: backendUrl, headers: locationHeaders, taskName: "CapgoLocationUpdate") } private func stringHeaders(from object: [String: Any]?) -> [String: String] { guard let object else { return [:] } var headers: [String: String] = [:] for (key, value) in object { if let string = value as? String { headers[key] = string } else if let number = value as? NSNumber { headers[key] = number.stringValue } else { headers[key] = String(describing: value) } } return headers } private func postJson(_ body: Data, to url: URL, headers: [String: String], taskName: String) { var request = URLRequest(url: url) request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") for (key, value) in headers { request.setValue(value, forHTTPHeaderField: key) } request.httpBody = body var backgroundTask = UIBackgroundTaskIdentifier.invalid backgroundTask = UIApplication.shared.beginBackgroundTask(withName: taskName) { if backgroundTask != .invalid { UIApplication.shared.endBackgroundTask(backgroundTask) backgroundTask = .invalid } } URLSession.shared.dataTask(with: request) { [weak self] _, response, _ in // KhorOps-Patch (29.10.2026): HTTP 410 = der Server sagt „Stopp“ (Dienst vorbei) if taskName == "CapgoLocationUpdate", let http = response as? HTTPURLResponse, http.statusCode == 410 { DispatchQueue.main.async { self?.stopFromServer() } } if backgroundTask != .invalid { UIApplication.shared.endBackgroundTask(backgroundTask) backgroundTask = .invalid } }.resume() } // KhorOps-Patch (29.10.2026): wie stop(), aber vom Server ausgelöst (ohne JavaScript) private func stopFromServer() { stopUpdatingLocation() locationManager?.delegate = nil locationManager = nil created = nil locationBackendUrl = nil locationHeaders = [:] minIntervalMs = 0 lastPostedLocationTime = nil if let callbackId = activeCallbackId { if let savedCall = bridge?.savedCall(withID: callbackId) { savedCall.keepAlive = false } activeCallbackId = nil } } private func startUpdatingLocation() { // Avoid unnecessary calls to startUpdatingLocation, which can // result in extraneous invocations of didFailWithError. if !isUpdatingLocation, let manager = locationManager { manager.startUpdatingLocation() isUpdatingLocation = true } } private func stopUpdatingLocation() { if isUpdatingLocation, let manager = locationManager { manager.stopUpdatingLocation() isUpdatingLocation = false } } private func isLocationValid(_ location: CLLocation) -> Bool { guard let created = created else { return allowStale } return ( allowStale || location.timestamp >= created ) } private func toRadians(_ degrees: Double) -> Double { return degrees * Double.pi / 180.0 } private func haversine(_ point1: [Double], _ point2: [Double]) -> Double { let lon1 = point1[0] let lat1 = point1[1] let lon2 = point2[0] let lat2 = point2[1] let dLat = toRadians(lat2 - lat1) let dLon = toRadians(lon2 - lon1) let aaa = sin(dLat / 2) * sin(dLat / 2) + cos(toRadians(lat1)) * cos(toRadians(lat2)) * sin(dLon / 2) * sin(dLon / 2) let ccc = 2 * atan2(sqrt(aaa), sqrt(1 - aaa)) return BackgroundGeolocation.earthRadiusMeters * ccc } private func distancePointToLineSegment(_ point: [Double], _ lineStart: [Double], _ lineEnd: [Double]) -> Double { // Calculate the distances between the three points using Haversine let distAB = haversine(point, lineStart) let distAC = haversine(point, lineEnd) let distBC = haversine(lineStart, lineEnd) // Handle the edge case where the line segment is a single point if distBC == 0 { return distAB } // Check if the angles at the line segment's endpoints are obtuse. // We use the Law of Cosines (c^2 = a^2 + b^2 - 2ab*cos(C)) // If cos(C) < 0, the angle is obtuse. // Angle at B (lineStart) let epsilon = Double.ulpOfOne let cosB = (pow(distAB, 2) + pow(distBC, 2) - pow(distAC, 2)) / (2 * distAB * distBC + epsilon) if cosB < 0 { return distAB } // Angle at C (lineEnd) let cosC = (pow(distAC, 2) + pow(distBC, 2) - pow(distAB, 2)) / (2 * distAC * distBC + epsilon) if cosC < 0 { return distAC } // If both angles are acute, the closest point is on the line segment itself. // We can calculate the distance (height of the triangle) using its area. // 1. Calculate the semi-perimeter of the triangle ABC let semi = (distAB + distAC + distBC) / 2 // 2. Calculate the area using Heron's formula let area = sqrt(max(0, semi * (semi - distAB) * (semi - distAC) * (semi - distBC))) // 3. The distance is the height of the triangle from point A to the base BC // Area = 0.5 * base * height => height = 2 * Area / base return (2 * area) / (distBC + epsilon) } private func distancePointToRoute(_ point: [Double]) -> Double { // If the route has less than 2 points, we can't form a segment. if plannedRoute.count < 2 { if plannedRoute.count == 1 { return haversine(point, plannedRoute[0]) } return Double.infinity // No line segments to measure against } var minDistance = Double.infinity for pointIndex in 0..<(plannedRoute.count - 1) { let lineStart = plannedRoute[pointIndex] let lineEnd = plannedRoute[pointIndex + 1] let distance = distancePointToLineSegment(point, lineStart, lineEnd) if distance < minDistance { minDistance = distance } } return minDistance } private func checkRouteDeviation(_ location: CLLocation) { guard audioPlayer != nil && plannedRoute.count > 0 else { return } let currentPoint = [location.coordinate.longitude, location.coordinate.latitude] let offRoute = distancePointToRoute(currentPoint) > distanceThreshold if offRoute && !isOffRoute { audioPlayer?.play() } isOffRoute = offRoute } public func locationManager( _ manager: CLLocationManager, didFailWithError error: Error ) { guard manager === locationManager, let callbackId = activeCallbackId, let call = self.bridge?.savedCall(withID: callbackId) else { return } if let clErr = error as? CLError { if clErr.code == .locationUnknown { // This error is sometimes sent by the manager if // it cannot get a fix immediately. return } else if clErr.code == .denied { stopUpdatingLocation() return call.reject( "Permission denied.", "NOT_AUTHORIZED" ) } } return call.reject(error.localizedDescription, nil, error) } public func locationManager( _ manager: CLLocationManager, didUpdateLocations locations: [CLLocation] ) { guard manager === locationManager, let location = locations.last, isLocationValid(location) else { return } // Native delivery does not depend on the bridge, so it keeps working // even if the WebView is gone. postLocation(location) guard let callbackId = activeCallbackId, let call = self.bridge?.savedCall(withID: callbackId) else { return } checkRouteDeviation(location) return call.resolve(formatLocation(location)) } public func locationManager( _ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus ) { if pendingPermissionRequestCall != nil && status != .notDetermined { resolvePendingPermissionRequest() } if let pendingCall = pendingGeofenceSetupCall { if status == .authorizedAlways { pendingGeofenceSetupTimeout?.cancel() pendingGeofenceSetupTimeout = nil pendingGeofenceSetupCall = nil pendingCall.resolve() } else if status == .denied || status == .restricted || status == .authorizedWhenInUse { pendingGeofenceSetupTimeout?.cancel() pendingGeofenceSetupTimeout = nil pendingGeofenceSetupCall = nil pendingCall.reject("Always location permission is required for geofencing", "NOT_AUTHORIZED") } } // If this method is called before the user decides on a permission, as // it is on iOS 14 when the permissions dialog is presented, we ignore // it. if manager === locationManager && status != .notDetermined { startUpdatingLocation() } } public func locationManager(_ manager: CLLocationManager, didStartMonitoringFor region: CLRegion) { guard manager === geofenceLocationManager else { return } if let pending = pendingGeofenceRegions.removeValue(forKey: region.identifier) { persistGeofenceRegion(pending.region, payload: pending.payload) pendingGeofenceAddCalls.removeValue(forKey: region.identifier)?.resolve() } manager.requestState(for: region) } public func locationManager(_ manager: CLLocationManager, monitoringDidFailFor region: CLRegion?, withError error: Error) { guard manager === geofenceLocationManager, let region = region else { return } pendingGeofenceRegions.removeValue(forKey: region.identifier) removePersistedGeofenceRegion(region.identifier) pendingGeofenceAddCalls.removeValue(forKey: region.identifier)?.reject( "Could not start monitoring the geofence", "MONITORING_FAILED", error ) let nsError = error as NSError notifyListeners( "geofenceError", data: [ "identifier": region.identifier, "message": error.localizedDescription, "code": nsError.code, "domain": nsError.domain ], retainUntilConsumed: true ) } public func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) { guard manager === geofenceLocationManager, region is CLCircularRegion else { return } handleGeofenceTransition(for: region, enter: true) } public func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) { guard manager === geofenceLocationManager, region is CLCircularRegion else { return } handleGeofenceTransition(for: region, enter: false) } public func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) { guard manager === geofenceLocationManager, region is CLCircularRegion else { return } if state == .inside { handleGeofenceTransition(for: region, enter: true) } } @objc override public func checkPermissions(_ call: CAPPluginCall) { DispatchQueue.main.async { call.resolve(self.permissionStatusDictionary()) } } @objc override public func requestPermissions(_ call: CAPPluginCall) { DispatchQueue.main.async { if self.pendingPermissionRequestCall != nil { return call.reject("A permission request is already in progress", "PERMISSION_REQUEST_IN_PROGRESS") } let permissions = call.getArray("permissions", String.self) ?? [ "location", "backgroundLocation", "notification" ] let requestBackground = permissions.contains("backgroundLocation") let requestLocation = permissions.contains("location") || requestBackground guard requestLocation || requestBackground else { return call.resolve(self.permissionStatusDictionary()) } let manager = self.ensureGeofenceLocationManager() let status = manager.authorizationStatus if requestBackground { if status == .authorizedAlways { return call.resolve(self.permissionStatusDictionary()) } if [.denied, .restricted].contains(status) { return call.resolve(self.permissionStatusDictionary()) } self.beginPermissionRequest(call, manager: manager, requestAlways: true, status: status) return } if [.authorizedWhenInUse, .authorizedAlways].contains(status) { return call.resolve(self.permissionStatusDictionary()) } if [.denied, .restricted].contains(status) { return call.resolve(self.permissionStatusDictionary()) } self.beginPermissionRequest(call, manager: manager, requestAlways: false, status: status) } } private func beginPermissionRequest( _ call: CAPPluginCall, manager: CLLocationManager, requestAlways: Bool, status: CLAuthorizationStatus ) { pendingPermissionRequestCall = call pendingPermissionRequestTimeout?.cancel() let timeout = DispatchWorkItem { [weak self] in guard let self = self, let pendingCall = self.pendingPermissionRequestCall else { return } self.pendingPermissionRequestCall = nil self.pendingPermissionRequestTimeout = nil pendingCall.resolve(self.permissionStatusDictionary()) } pendingPermissionRequestTimeout = timeout if requestAlways { manager.requestAlwaysAuthorization() if status == .authorizedWhenInUse { DispatchQueue.main.asyncAfter(deadline: .now() + 30, execute: timeout) } } else { manager.requestWhenInUseAuthorization() } } private func resolvePendingPermissionRequest() { pendingPermissionRequestTimeout?.cancel() pendingPermissionRequestTimeout = nil guard let pendingCall = pendingPermissionRequestCall else { return } pendingPermissionRequestCall = nil pendingCall.resolve(permissionStatusDictionary()) } private func permissionStatusDictionary() -> [String: Any] { let status = ensureGeofenceLocationManager().authorizationStatus var result: [String: Any] = [:] switch status { case .notDetermined: result["location"] = "prompt" result["backgroundLocation"] = "prompt" case .restricted, .denied: result["location"] = "denied" result["backgroundLocation"] = "denied" case .authorizedWhenInUse: result["location"] = "granted" result["backgroundLocation"] = "when_in_use" case .authorizedAlways: result["location"] = "granted" result["backgroundLocation"] = "granted" @unknown default: result["location"] = "prompt" result["backgroundLocation"] = "prompt" } return result } @objc func getPluginVersion(_ call: CAPPluginCall) { call.resolve(["version": self.pluginVersion]) } }