Last active
July 2, 2025 20:30
-
-
Save Cookizza/05d8d4cc822e8933aea3583249ec30e8 to your computer and use it in GitHub Desktop.
Expo background location
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // This is a service which essentially runs outside of your react app | |
| import { type LocationObject } from 'expo-location'; | |
| const LocationService = () => { | |
| let subscribers: any[] = []; | |
| let location: LocationObject | {} = {}; | |
| return { | |
| subscribe: (sub: (p: LocationObject) => void) => subscribers.push(sub), | |
| setLocation: (coords: LocationObject) => { | |
| location = coords; | |
| subscribers.forEach((sub) => sub(location)); | |
| }, | |
| unsubscribe: (sub: (p: LocationObject) => void) => { | |
| subscribers = subscribers.filter((_sub) => _sub !== sub); | |
| }, | |
| }; | |
| }; | |
| export const locationService = LocationService(); | |
| ------------------ | |
| const LOCATION_TASK_NAME = 'background-location-task'; | |
| // This is the background task, it should be very simple only sending data to your service | |
| TaskManager.defineTask<any>(LOCATION_TASK_NAME, ({ data, error }) => { | |
| if (error) { | |
| console.log('location background task error: ', error); | |
| return; | |
| } | |
| if (data) { | |
| locationService.setLocation(data.locations[0]); | |
| } | |
| }); | |
| ------------------ | |
| // Call this when you want to start background tracking | |
| const runBackgroundTask = useCallback(async () => { | |
| await Location.startLocationUpdatesAsync(LOCATION_TASK_NAME, { | |
| accuracy: Location.Accuracy.Balanced, | |
| timeInterval: 5000, | |
| distanceInterval: 5, | |
| foregroundService: { | |
| notificationTitle: 'Realtime Location', | |
| notificationBody: 'Sharing your location with your friends', | |
| }, | |
| showsBackgroundLocationIndicator: true, | |
| pausesUpdatesAutomatically: false, | |
| }); | |
| }, []); | |
| ------------------ | |
| // This is how your app receives updates via the location service. | |
| const locationServiceUpdate = useCallback((position: LocationObject) => { | |
| setLocation(position); //This should be your actual state that you use in the app | |
| }, []); | |
| useEffect(() => { | |
| locationService.subscribe(locationServiceUpdate); | |
| runBackgroundTask().then(); | |
| return () => locationService.unsubscribe(locationServiceUpdate); | |
| }, [locationServiceUpdate, runBackgroundTask]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment