Hello everyone! Let me explain my problem with an issue template.
- SDK Version: 36
- Platforms: Android 9 (Xiaomi Redmi Note 7 MIUI11) and Android 9 emulator (Google Pixel 2)
Steps to reproduce:
- TaskManager.defineTask() in App.js outside of component class.
- Register task with Location.startLocationUpdatesAsync() anywhere (normal or async function or lifecycle method ot useEffect hook).
- Log gotten results inside Task.
Expected behavior:
Background task should be started. On every location update there should be logged new locations array containg freshly caught location regardless of app being open or minimized.
Actual behavior:
TaskManager.defineTask must be called during initialization phase! error is logged in the console. If Location.startLocationUpdatesAsync() is called in async function it also throws error in Client as well. Location is checked once or twice per app refresh.
My code:
import React, { Component } from 'react';
import { Platform, Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
import * as Location from 'expo-location';
import * as Permissions from 'expo-permissions';
import * as TaskManager from 'expo-task-manager';
export default class App extends Component {
state = {
location: null,
errorMessage: null,
};
constructor() {
super();
this._ensurePermissionGranted();
this._startLocationUpdates();
}
_startLocationUpdates = () => {
Location.startLocationUpdatesAsync('watch', {
foregroundService: {
notificationTitle: 'Geotracker',
notificationBody: 'Tracking enabled'
}
});
}
_ensurePermissionGranted = async () => {
let { status } = await Permissions.askAsync(Permissions.LOCATION);
if (status !== 'granted') {
this.setState({
errorMessage: 'Permission to access location was denied',
});
}
}
render() {
let text = 'Waiting..';
if (this.state.errorMessage) {
text = this.state.errorMessage;
} else if (this.state.location) {
text = JSON.stringify(this.state.location);
}
return (
<View style={styles.container}>
<Text style={styles.paragraph}>{text}</Text>
</View>
);
}
}
TaskManager.defineTask('watch', ({ data: { locations = [] }, error }) => {
if(error) {
return console.error(error)
}
console.log(locations.reverse()[0]);
})
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
},
paragraph: {
margin: 24,
fontSize: 18,
textAlign: 'center',
},
});
This code is as simple as it can get to show what exactly is not working. Whole project is fresh out of expo init command and code above is everything App.js consists of.