react-native-background-geolocation
react-native-background-geolocation copied to clipboard
App crashed while it's in background
Your Environment
- Plugin version:^4.9.3"
- Platform: Android
- OS version: 12 SKQ1.211019.001
- Device manufacturer / model: Xiaomi Redmi Note 9 Pro
- React Native version (
react-native -v
):0.70.6 - Plugin config
import BackgroundGeolocation, {
Subscription,
State,
Config,
Location,
MotionChangeEvent,
CurrentPositionRequest,
} from 'react-native-background-geolocation';
import { setRecordedDriverCoords, updateCurrentLocation, updateOnDutyLatLon } from '@store/actions';
import { store } from '@store';
import i18n from '@i18n';
let onLocation: Subscription;
let onMotionChange: Subscription;
export const bgGeoStart = () => {
onLocation = BackgroundGeolocation.onLocation(async (location: Location) => {
const state = store.getState();
const refreshToken = state.auth.accessToken;
const lat = location?.coords?.latitude;
const lng = location?.coords?.longitude;
if (lat && lng) {
const coordinates = {
latitude: lat,
longitude: lng,
timeStamp: location.timestamp,
carSpeed: location.coords.speed,
};
const driverCoords: string = '%7B' + lat + '%2C' + lng + '%7D';
store.dispatch(updateCurrentLocation(coordinates));
store.dispatch(setRecordedDriverCoords(driverCoords));
console.log('Coords', coordinates);
}
if (refreshToken) {
store.dispatch(
updateOnDutyLatLon({
description: 'foreground location',
onDuty: state.user.profile.onDuty,
}),
);
}
});
onMotionChange = BackgroundGeolocation.onMotionChange((event: MotionChangeEvent) => {
if (!event.isMoving) {
console.log('[onMotionChange] Device has just STOPPED: ', event.location);
}
});
const backgroundGeoConfig: Config = {
// Geolocation Config
desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
// Activity Recognition
distanceFilter: 50,
notification: {
title: '...',
text: 'trackingOnline',
smallIcon: 'mipmap/ic_notification',
},
stopTimeout: 5,
// Application config
debug: false, // <-- enable this hear sounds for background-geolocation life-cycle.
logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
enableHeadless: true,
stopOnTerminate: false, // <-- Allow the background-service to continue tracking when user closes the app.
startOnBoot: true, // <-- Auto start tracking when device is powered-up.
batchSync: false, // <-- [Default: false] Set true to sync locations to server in a single HTTP request.
autoSync: true, // <-- [Default: true] Set true to sync each location to server as it arrives.
locationAuthorizationRequest: 'Always',
backgroundPermissionRationale: {
title: i18n.t<string>('Common:permissionTitle'),
message: i18n.t<string>('Common:permissionMessage'),
positiveAction: i18n.t<string>('Common:permissionPositive'),
negativeAction: i18n.t<string>('Common:permissionNegative'),
},
};
BackgroundGeolocation.ready(backgroundGeoConfig).then(async (state: State) => {
console.log('- BackgroundGeolocation is configured and ready: ', state.enabled);
const location = await getCurrentPosition();
console.log('ready getCurrentPosition', location);
BackgroundGeolocation.start();
});
};
const currentPositionConfig: CurrentPositionRequest = {
timeout: 30, // 30 second timeout to fetch location
maximumAge: 5000, // Accept the last-known-location if not older than 5000 ms.
desiredAccuracy: 10, // Try to fetch a location with an accuracy of `10` meters.
samples: 1, // How many location samples to attempt.
extras: {
// Custom meta-data.
route_id: 123,
},
};
export const getCurrentPosition = () => {
return new Promise(resolve => {
BackgroundGeolocation.getCurrentPosition(
currentPositionConfig,
location => {
resolve(location);
},
error => {
resolve(error);
},
);
});
};
export const bgGeoStop = () => {
onLocation.remove();
onMotionChange.remove();
BackgroundGeolocation.stop();
};
Expected Behavior
App would work normally while its in background
Actual Behavior
App crashed while it is in background
Steps to Reproduce
1- This is the code works in index.js to get location while app is in background
/**
* @format
*/
import { AppRegistry, LogBox } from 'react-native';
import BackgroundGeolocation from 'react-native-background-geolocation';
import { getCurrentPosition } from '@utils/backgroundLocation';
import { updateCurrentLocation, updateOnDutyLatLon } from '@store/actions';
import App from './src/App';
import { name as appName } from './app.json';
import { store } from '@store';
let HeadlessTask = async event => {
let params = event.params;
const state = store.getState();
if (params.coords) {
if (params.coords.latitude && params.coords.longitude) {
let coordinates = {
latitude: params?.coords?.latitude,
longitude: params?.coords?.longitude,
timeStamp: params?.timestamp,
carSpeed: params?.coords?.speed,
};
await store.dispatch(updateCurrentLocation(coordinates));
}
}
store.dispatch(updateOnDutyLatLon({ description: 'background location', onDuty: state.user.profile.onDuty }));
switch (event.name) {
case 'heartbeat':
// Use await for async tasks
await getCurrentPosition();
break;
}
};
BackgroundGeolocation.registerHeadlessTask(HeadlessTask);
LogBox.ignoreAllLogs(true);
AppRegistry.registerComponent(appName, () => App);
Context
Debug logs
PASTE_YOUR_LOGS_HERE