### Run Example Application
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/example/README.md
Commands to install dependencies and launch the example app on an Android device or emulator.
```bash
# Install dependencies
yarn
# Start Metro bundler
yarn example start
# Run on Android device/emulator
yarn example android
```
--------------------------------
### Install Pods and Run iOS Example
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/website/docs/development/contributing.md
Installs iOS dependencies using CocoaPods and then runs the example application. This is necessary after modifying native iOS code.
```sh
cd example/ios && pod install && cd ../..
yarn example ios
```
--------------------------------
### Start Example App Metro Bundler
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/website/docs/development/contributing.md
Starts the Metro bundler for the example application. This allows for live reloading of JavaScript changes.
```sh
yarn example start
```
--------------------------------
### Geofencing Quick Start
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/website/docs/guides/geofencing.md
A minimal example demonstrating how to register a geofence and listen for transition events.
```APIDOC
## Geofencing Quick Start
### Description
This example shows how to initialize geofencing, add a geofence, and react to transition events.
### Method
N/A (Component Example)
### Endpoint
N/A
### Parameters
N/A
### Request Example
```typescript
import React, { useState } from 'react';
import { View, Text, Button } from 'react-native';
import {
useGeofencing,
useGeofenceEvents,
GeofenceTransitionType,
} from '@gabriel-sisjr/react-native-background-location';
function GeofenceDemo() {
const [enterCount, setEnterCount] = useState(0);
const { geofences, addGeofence, maxGeofences } = useGeofencing();
useGeofenceEvents({
onTransition: (event) => {
if (event.transitionType === GeofenceTransitionType.ENTER) {
setEnterCount((prev) => prev + 1);
}
},
});
const handleAddGeofence = async () => {
await addGeofence({
identifier: 'office',
latitude: -23.5505,
longitude: -46.6333,
radius: 200,
});
};
return (
Active: {geofences.length} / {maxGeofences}Enter events: {enterCount}
);
}
```
### Response
N/A
```
--------------------------------
### Install and Link Package
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/README.md
Install the package and its iOS dependencies. Autolinking handles most setup, but manual Info.plist configuration is required for iOS.
```bash
yarn add @gabriel-sisjr/react-native-background-location
cd ios && pod install
```
--------------------------------
### Complete Trip Management Example
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/website/docs/guides/background-tracking.md
A comprehensive example showcasing the lifecycle of a trip, including starting, stopping, refreshing locations, and clearing data using the `useBackgroundLocation` hook.
```APIDOC
## Complete Trip Management Example
```typescript
import {
useBackgroundLocation,
LocationAccuracy,
NotificationPriority,
} from '@gabriel-sisjr/react-native-background-location';
import type { TrackingOptions } from '@gabriel-sisjr/react-native-background-location';
function TripManager() {
const {
isTracking,
tripId,
locations,
startTracking,
stopTracking,
refreshLocations,
clearCurrentTrip,
} = useBackgroundLocation();
const handleStartTrip = async () => {
const options: TrackingOptions = {
accuracy: LocationAccuracy.HIGH_ACCURACY,
updateInterval: 5000,
distanceFilter: 25,
notificationOptions: {
title: 'Trip Tracking',
text: 'Tracking your trip in background',
priority: NotificationPriority.LOW,
},
};
const id = await startTracking(undefined, options);
if (id) {
console.log('Trip started:', id);
// Save trip ID to your backend
await saveTrip({ id, startedAt: Date.now() });
}
};
const handleEndTrip = async () => {
if (tripId) {
// Upload locations before stopping
await uploadLocations(tripId, locations);
await clearCurrentTrip();
await stopTracking();
}
};
return (
{isTracking && (
<>
>
)}
);
}
```
```
--------------------------------
### Install the library
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/website/static/llms-full.txt
Install the package using yarn or npm.
```bash
yarn add @gabriel-sisjr/react-native-background-location
# or
npm install @gabriel-sisjr/react-native-background-location
```
--------------------------------
### Run Example App on Android
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/website/docs/development/contributing.md
Builds and runs the example application on an Android device or emulator.
```sh
yarn example android
```
--------------------------------
### Implement Background Tracking with Notifications
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/website/docs/guides/notification-customization.md
A complete example demonstrating how to start background tracking with custom notification options and handle notification actions.
```typescript
import React from 'react';
import { View, Text, Button } from 'react-native';
import {
useBackgroundLocation,
useLocationUpdates,
LocationAccuracy,
NotificationPriority,
stopTracking,
} from '@gabriel-sisjr/react-native-background-location';
function NotificationDemo() {
const { startTracking, isTracking } = useBackgroundLocation();
useLocationUpdates({
onNotificationAction: (event) => {
if (event.actionId === 'stop') {
stopTracking();
}
},
});
const handleStart = async () => {
await startTracking(undefined, {
accuracy: LocationAccuracy.HIGH_ACCURACY,
updateInterval: 5000,
notificationOptions: {
title: 'Delivery Active',
text: 'En route to destination',
priority: NotificationPriority.LOW,
channelName: 'Delivery Tracking',
color: '#2196F3',
showTimestamp: true,
subtext: 'Background tracking',
actions: [
{ id: 'stop', label: 'Stop Tracking' },
],
},
});
};
return (
Tracking: {isTracking ? 'Active' : 'Inactive'}
);
}
```
--------------------------------
### Run Example App on iOS
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/website/docs/development/contributing.md
Builds and runs the example application on an iOS simulator or physical device.
```sh
yarn example ios
```
--------------------------------
### Test installation in a new project
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/website/docs/development/publishing.md
Verify the package installation process in a clean React Native environment.
```bash
npx react-native init TestApp
cd TestApp
npm install @gabriel-sisjr/react-native-background-location
```
--------------------------------
### Example Application Execution Commands
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/CONTRIBUTING.md
Commands to manage the example application lifecycle, including starting the Metro packager and running the app on specific platforms.
```shell
yarn example start
yarn example android
yarn example ios
```
--------------------------------
### Project Directory Structure
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/example/README.md
Overview of the example application file structure.
```text
example/
src/
App.tsx # Main app with tracking controls and live map
android/ # Android-specific configuration
ios/ # iOS configuration (stub)
```
--------------------------------
### Beta Version Format Examples
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/website/docs/development/ci-cd.md
Shows the structure of automatically generated beta version strings, including timestamps and commit SHAs, as well as custom suffix examples.
```text
0.2.0-beta.20251026143022.a1b2c3d
|--- timestamp ---|-- SHA --|
Or with custom suffix:
0.2.0-rc1
0.2.0-beta1
```
--------------------------------
### Install Beta Version of Package
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/website/docs/development/publishing.md
Install the beta version of the package using npm or yarn to test pre-release features. The '@beta' tag specifies the pre-release channel.
```bash
npm install @gabriel-sisjr/react-native-background-location@beta
# or
yarn add @gabriel-sisjr/react-native-background-location@beta
```
--------------------------------
### Project Setup and Dependency Installation
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/CONTRIBUTING.md
Commands to initialize the development environment. This installs all dependencies for the monorepo using Yarn workspaces.
```shell
yarn
```
--------------------------------
### Install iOS Pods
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/website/docs/getting-started/installation.md
After completing iOS-specific Info.plist and Xcode configurations, install the necessary pods using the command line. This step is crucial for linking native iOS dependencies.
```bash
cd ios && pod install && cd ..
```
--------------------------------
### Install CocoaPods Dependencies
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/website/docs/getting-started/ios-setup.md
Commands to install or clean and reinstall project dependencies.
```bash
cd ios && pod install && cd ..
```
```bash
cd ios
rm -rf Pods Podfile.lock
pod install --repo-update
cd ..
```
--------------------------------
### Before: Notification Options (v0.10.x)
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/website/docs/migration/v0-12-0.md
Example of how notification-related options were passed directly to `startTracking` in v0.10.x.
```typescript
startTracking({
updateInterval: 5000,
notificationTitle: 'Location Tracking',
notificationText: 'Tracking in background',
notificationChannelName: 'Background Location',
notificationChannelId: 'location_channel',
notificationPriority: NotificationPriority.LOW,
notificationSmallIcon: 'ic_notification',
notificationLargeIcon: 'ic_notification_large',
notificationColor: '#4CAF50',
notificationShowTimestamp: true,
notificationSubtext: 'Example',
notificationActions: [{ id: 'stop', label: 'Stop' }],
});
```
--------------------------------
### Complete App Example with Background Location Tracking
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/website/docs/getting-started/quick-start.md
This example shows a full React Native application setup for background location tracking. It includes permission handling, tracking configuration, error management, and data upload functionality. Use this as a comprehensive template for your project.
```tsx
import React, { useEffect } from 'react';
import { View, Text, Button, Alert, StyleSheet } from 'react-native';
import {
useLocationPermissions,
useBackgroundLocation,
useLocationUpdates,
LocationAccuracy,
NotificationPriority,
type TrackingOptions,
} from '@gabriel-sisjr/react-native-background-location';
const TRACKING_OPTIONS: TrackingOptions = {
accuracy: LocationAccuracy.HIGH_ACCURACY,
updateInterval: 5000,
fastestInterval: 3000,
distanceFilter: 50,
notificationOptions: {
title: 'Trip Recording',
text: 'Recording your route in the background',
priority: NotificationPriority.LOW,
channelName: 'Trip Tracking',
},
};
export default function App() {
const { permissionStatus, requestPermissions, isRequesting } =
useLocationPermissions();
const {
startTracking,
stopTracking,
isTracking,
tripId,
locations,
error,
clearError,
refreshLocations,
clearCurrentTrip,
} = useBackgroundLocation({
onTrackingStart: (id) => console.log('Tracking started:', id),
onTrackingStop: () => console.log('Tracking stopped'),
onError: (err) => Alert.alert('Tracking Error', err.message),
});
const { lastLocation } = useLocationUpdates({
onLocationUpdate: (loc) => {
console.log(`[${new Date(loc.timestamp).toISOString()}]`,
loc.latitude, loc.longitude);
},
onLocationWarning: (warning) => {
console.warn(`[${warning.type}] ${warning.message}`);
},
});
// Show errors
useEffect(() => {
if (error) {
Alert.alert('Error', error.message, [
{ text: 'Dismiss', onPress: clearError },
]);
}
}, [error, clearError]);
const handleToggleTracking = async () => {
if (isTracking) {
await stopTracking();
} else {
await startTracking(undefined, TRACKING_OPTIONS);
}
};
const handleUploadAndClear = async () => {
if (!tripId || locations.length === 0) return;
try {
// Upload to your server
await fetch('https://your-api.com/trips', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
tripId,
locations: locations.map((loc) => ({
latitude: parseFloat(loc.latitude),
longitude: parseFloat(loc.longitude),
timestamp: loc.timestamp,
})),
}),
});
await clearCurrentTrip();
Alert.alert('Success', 'Trip data uploaded and cleared');
} catch (err) {
Alert.alert('Upload Failed', 'Please try again later');
}
};
// Permission screen
if (!permissionStatus.location.hasPermission) {
return (
Location Permission Required
);
}
return (
{isTracking ? 'Tracking Active' : 'Ready'}
{tripId && Trip: {tripId}}
Points: {locations.length}
{lastLocation && (
Last: {lastLocation.latitude}, {lastLocation.longitude}
)}
{isTracking && (
)}
{!isTracking && locations.length > 0 && (
)}
);
}
const styles = StyleSheet.create({
container: { flex: 1, justifyContent: 'center', padding: 20 },
title: { fontSize: 22, fontWeight: 'bold', textAlign: 'center', marginBottom: 16 },
info: { fontSize: 14, textAlign: 'center', marginBottom: 8 },
buttonGroup: { marginTop: 20, gap: 12 },
});
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/website/docs/development/contributing.md
Installs all necessary dependencies for the monorepo using Yarn workspaces. This command should be run in the root directory.
```sh
yarn
```
--------------------------------
### startTracking
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/website/docs/api-reference/functions.md
Starts location tracking in the background for a specific trip.
```APIDOC
## startTracking
### Description
Starts location tracking in the background for a specific trip. When the native module is not available, logs a warning and returns a fallback tripId.
### Parameters
#### Path Parameters
- **tripIdOrOptions** (string | TrackingOptions) - Optional - Either a trip identifier string or tracking configuration options.
- **options** (TrackingOptions) - Optional - Tracking configuration options.
### Response
#### Success Response (200)
- **tripId** (string) - The effective tripId (either the provided one or the auto-generated one).
```
--------------------------------
### Complete Trip Management with useBackgroundLocation Hook
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/website/docs/guides/background-tracking.md
A comprehensive example demonstrating the full lifecycle of trip management using the `useBackgroundLocation` hook. It covers starting tracking with custom options, handling trip IDs, uploading locations, clearing data, and stopping tracking.
```javascript
import {
useBackgroundLocation,
LocationAccuracy,
NotificationPriority,
} from '@gabriel-sisjr/react-native-background-location';
import type { TrackingOptions } from '@gabriel-sisjr/react-native-background-location';
function TripManager() {
const {
isTracking,
tripId,
locations,
startTracking,
stopTracking,
refreshLocations,
clearCurrentTrip,
} = useBackgroundLocation();
const handleStartTrip = async () => {
const options: TrackingOptions = {
accuracy: LocationAccuracy.HIGH_ACCURACY,
updateInterval: 5000,
distanceFilter: 25,
notificationOptions: {
title: 'Trip Tracking',
text: 'Tracking your trip in background',
priority: NotificationPriority.LOW,
},
};
const id = await startTracking(undefined, options);
if (id) {
console.log('Trip started:', id);
// Save trip ID to your backend
await saveTrip({ id, startedAt: Date.now() });
}
};
const handleEndTrip = async () => {
if (tripId) {
// Upload locations before stopping
await uploadLocations(tripId, locations);
await clearCurrentTrip();
await stopTracking();
}
};
return (
{isTracking && (
<>
>
)}
);
}
```
--------------------------------
### Auto-Start Tracking
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/website/docs/guides/background-tracking.md
Demonstrates how to configure the `useBackgroundLocation` hook to automatically start tracking location updates when the component mounts.
```APIDOC
## Auto-Start Tracking
The `useBackgroundLocation` hook supports auto-starting on mount.
```typescript
function AutoTrackingScreen() {
const { isTracking, locations } = useBackgroundLocation({
autoStart: true,
options: {
accuracy: LocationAccuracy.HIGH_ACCURACY,
updateInterval: 5000,
notificationOptions: {
priority: NotificationPriority.LOW,
},
},
onError: (error) => {
Alert.alert('Error', error.message);
},
});
return (
Auto-tracking: {isTracking ? 'Active' : 'Inactive'}Points collected: {locations.length}
);
}
```
```
--------------------------------
### Add Single Geofence
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/website/docs/guides/geofencing.md
Example of how to add a single geofence to the monitoring system.
```APIDOC
## POST /api/geofences (Conceptual)
### Description
Adds a single geofence to be monitored by the background location service.
### Method
POST (Conceptual)
### Endpoint
`/api/geofences` (Conceptual)
### Parameters
#### Request Body
- **identifier** (string) - Required - Unique identifier for the geofence.
- **latitude** (number) - Required - The latitude of the geofence center.
- **longitude** (number) - Required - The longitude of the geofence center.
- **radius** (number) - Required - The radius of the geofence in meters.
### Request Example
```typescript
import { addGeofence } from '@gabriel-sisjr/react-native-background-location';
await addGeofence({
identifier: 'office',
latitude: -23.5505,
longitude: -46.6333,
radius: 200,
});
```
### Response
#### Success Response (200)
Indicates the geofence was successfully added.
#### Response Example
```json
{
"success": true,
"message": "Geofence added successfully"
}
```
```
--------------------------------
### Install Package with npm or yarn
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/website/docs/getting-started/installation.md
Use npm or yarn to add the background location library to your project. Autolinking is used, so no manual linking is required.
```bash
# Using npm
npm install @gabriel-sisjr/react-native-background-location
# Using yarn
yarn add @gabriel-sisjr/react-native-background-location
```
--------------------------------
### Define Usage Description Strings
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/website/docs/getting-started/ios-setup.md
Examples of compliant and non-compliant usage description strings for App Store review.
```xml
NSLocationWhenInUseUsageDescriptionWe use your location to show your current position on the map
and record trip routes while you are using the app.NSLocationAlwaysAndWhenInUseUsageDescriptionWe use your location in the background to continuously record
your trip route, even when the app is not visible. This ensures
complete and accurate trip records for fleet management.
```
```xml
This app uses your location.Required for CLLocationManager background updates via
CoreLocation framework.
```
--------------------------------
### Start Tracking
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/website/docs/getting-started/quick-start.md
Initiates background location tracking. You can start with default options, custom accuracy, update intervals, distance filters, or provide a custom trip ID.
```APIDOC
## Start Tracking
### Description
Initiates background location tracking. This function can be called with default options, custom accuracy, update intervals, distance filters, or a custom trip ID.
### Method
`startTracking(tripId?: string, options?: TrackingOptions)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
#### `tripId` (string, Optional)
- A custom identifier for the tracking session.
#### `options` (object, Optional)
- **accuracy** (LocationAccuracy) - The desired location accuracy (e.g., `LocationAccuracy.HIGH_ACCURACY`, `LocationAccuracy.BALANCED_POWER_ACCURACY`).
- **updateInterval** (number) - The interval in milliseconds to receive location updates.
- **distanceFilter** (number) - The minimum distance in meters to trigger a location update.
### Request Example
```javascript
// Start with default options
const id = await startTracking();
// Start with custom options
const id = await startTracking(undefined, {
accuracy: LocationAccuracy.HIGH_ACCURACY,
updateInterval: 5000,
distanceFilter: 50,
});
// Start with a custom trip ID
const id = await startTracking('my-trip-123', {
accuracy: LocationAccuracy.BALANCED_POWER_ACCURACY,
});
```
### Response
#### Success Response
- **id** (string) - The ID of the tracking session.
#### Response Example
```json
"some-trip-id-12345"
```
```
--------------------------------
### Configure NotificationOptions in v0.10.x
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/BREAKING_CHANGES.md
Example of the legacy flat notification configuration structure used prior to v0.12.0.
```typescript
startTracking({
updateInterval: 5000,
notificationTitle: 'Location Tracking',
notificationText: 'Tracking in background',
notificationChannelName: 'Background Location',
notificationChannelId: 'location_channel',
notificationPriority: NotificationPriority.LOW,
notificationSmallIcon: 'ic_notification',
notificationLargeIcon: 'ic_notification_large',
notificationColor: '#4CAF50',
notificationShowTimestamp: true,
notificationSubtext: 'Example',
notificationActions: [{ id: 'stop', label: 'Stop' }],
});
```
--------------------------------
### Implement Complete Permission Flow
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/website/docs/guides/permission-handling.md
A comprehensive example demonstrating how to handle granted, blocked, and undetermined permission states within a React component.
```typescript
import React from 'react';
import { View, Text, Button, Linking, Alert } from 'react-native';
import { useLocationPermissions } from '@gabriel-sisjr/react-native-background-location';
function App() {
const {
permissionStatus,
requestPermissions,
isRequesting,
} = useLocationPermissions();
// Step 1: Check if permissions are granted
if (permissionStatus.hasAllPermissions) {
return ;
}
// Step 2: Handle blocked state
if (permissionStatus.location.status === 'blocked') {
return (
Location Access Required
Location permissions have been permanently denied.
Please enable them in Settings to use this app.
);
}
// Step 3: Handle denied / undetermined states
return (
Welcome
This app needs location access to track your trips in the background.
{/* Show individual permission states */}
Location: {permissionStatus.location.status}Notification: {permissionStatus.notification.status}
);
}
```
--------------------------------
### Quick Start: Start Background Tracking
Source: https://github.com/gabriel-sisjr/react-native-background-location/blob/develop/README.md
Initiate background location tracking with a specified trip ID and distance filter. Ensure location permissions are handled prior to calling this function.
```tsx
import {
startTracking,
useLocationUpdates,
} from '@gabriel-sisjr/react-native-background-location';
function App() {
const { locations } = useLocationUpdates();
return (