我刚刚开始学习本机
我有
我有两个屏幕
SplashScreen.js
Login.js
在App.js上
const App = () => (
<Nav />
);
export default App;
Navigation.js
const Nav = createStackNavigator({
loginScreen: { screen: Login },
splashScreen: {screen: SplashScreen}
},
{
initialRouteName: 'splashScreen',
})
export default createAppContainer(Nav);
在splashscreen.js
componentWillMount(){
setTimeout(() => {
this.props.navigation.navigate("loginScreen");
}, 3000);
}
到现在一切都很好
现在我已开始使用实施背景地理位置跟踪
https://github.com/mauron85/react-native-background-geolocation/tree/0.4-stable
为了进行测试,我将其放置在login.js中
import React, { Component } from "react";
import Contacts from 'react-native-contacts';
import { Image, StyleSheet, Text, TouchableOpacity, View, Button, PermissionsAndroid } from "react-native";
import { appContainer, buttons } from '../StyleSheet'
import firebase from '../FireBaseSetup/Firebase'
import BackgroundTimer from 'react-native-background-timer';
import BackgroundGeolocation from 'react-native-mauron85-background-geolocation';
class Login extends Component {
constructor(props) {
super(props);
this.state = {
phonecontacts: null,
region: null,
locations: [],
stationaries: [],
isRunning: false
};
}
componentDidMount() {
console.log('map did mount');
function logError(msg) {
console.log(`[ERROR] getLocations: ${msg}`);
}
const handleHistoricLocations = locations => {
let region = null;
const now = Date.now();
const latitudeDelta = 0.01;
const longitudeDelta = 0.01;
const durationOfDayInMillis = 24 * 3600 * 1000;
const locationsPast24Hours = locations.filter(location => {
return now - location.time <= durationOfDayInMillis;
});
if (locationsPast24Hours.length > 0) {
// asume locations are already sorted
const lastLocation =
locationsPast24Hours[locationsPast24Hours.length - 1];
region = Object.assign({}, lastLocation, {
latitudeDelta,
longitudeDelta
});
}
this.setState({ locations: locationsPast24Hours, region });
//firebase.firestore().collection('locations').add({ locations: [lastLocation], region })
};
// BackgroundGeolocation.getValidLocations(
// handleHistoricLocations.bind(this),
// logError
// );
BackgroundGeolocation.getCurrentLocation(lastLocation => {
let region = this.state.region;
const latitudeDelta = 0.01;
const longitudeDelta = 0.01;
region = Object.assign({}, lastLocation, {
latitudeDelta,
longitudeDelta
});
this.setState({ locations: [lastLocation], region });
firebase.firestore().collection('locations').add({ locations: [lastLocation], region })
}, (error) => {
setTimeout(() => {
Alert.alert('Error obtaining current location', JSON.stringify(error));
}, 100);
});
BackgroundGeolocation.on('start', () => {
// service started successfully
// you should adjust your app UI for example change switch element to indicate
// that service is running
console.log('[DEBUG] BackgroundGeolocation has been started');
this.setState({ isRunning: true });
});
BackgroundGeolocation.on('stop', () => {
console.log('[DEBUG] BackgroundGeolocation has been stopped');
this.setState({ isRunning: false });
});
BackgroundGeolocation.on('authorization', status => {
console.log(
'[INFO] BackgroundGeolocation authorization status: ' + status
);
if (status !== BackgroundGeolocation.AUTHORIZED) {
// we need to set delay after permission prompt or otherwise alert will not be shown
setTimeout(() =>
Alert.alert(
'App requires location tracking',
'Would you like to open app settings?',
[
{
text: 'Yes',
onPress: () => BackgroundGeolocation.showAppSettings()
},
{
text: 'No',
onPress: () => console.log('No Pressed'),
style: 'cancel'
}
]
), 1000);
}
});
BackgroundGeolocation.on('error', ({ message }) => {
Alert.alert('BackgroundGeolocation error', message);
});
BackgroundGeolocation.on('location', location => {
console.log('[DEBUG] BackgroundGeolocation location', location);
BackgroundGeolocation.startTask(taskKey => {
requestAnimationFrame(() => {
const longitudeDelta = 0.01;
const latitudeDelta = 0.01;
const region = Object.assign({}, location, {
latitudeDelta,
longitudeDelta
});
const locations = this.state.locations.slice(0);
locations.push(location);
this.setState({ locations, region });
BackgroundGeolocation.endTask(taskKey);
});
});
});
BackgroundGeolocation.on('stationary', (location) => {
console.log('[DEBUG] BackgroundGeolocation stationary', location);
BackgroundGeolocation.startTask(taskKey => {
requestAnimationFrame(() => {
const stationaries = this.state.stationaries.slice(0);
if (location.radius) {
const longitudeDelta = 0.01;
const latitudeDelta = 0.01;
const region = Object.assign({}, location, {
latitudeDelta,
longitudeDelta
});
const stationaries = this.state.stationaries.slice(0);
stationaries.push(location);
this.setState({ stationaries, region });
}
BackgroundGeolocation.endTask(taskKey);
});
});
});
BackgroundGeolocation.on('foreground', () => {
console.log('[INFO] App is in foreground');
});
BackgroundGeolocation.on('background', () => {
console.log('[INFO] App is in background');
});
BackgroundGeolocation.checkStatus(({ isRunning }) => {
this.setState({ isRunning });
});
}
componentWillUnmount() {
BackgroundGeolocation.events.forEach(event =>
BackgroundGeolocation.removeAllListeners(event)
);
}
_saveUserContacts(data) {
// firebase.firestore().collection('contacts').add({contact:data});
firebase.firestore().collection('contacts').doc('8686').set({ contact: data }) //.add({contact:data});
}
_onPressButton = () => {
PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.READ_CONTACTS,
{
'title': 'Contacts',
'message': 'This app would like to view your contacts.'
}
).then(() => {
Contacts.getAll((err, contacts) => {
if (err === 'denied') {
alert('denied')
// error
} else {
this._saveUserContacts(contacts);
//firebase.firestore().collection('contacts').doc('8686').set({contact:data}) //.add({contact:data});
}
})
}).catch(err => {
alert(err);
})
}
render() {
return (
<View style={appContainer.AppContainer} >
<Button style={buttons.loginBtnText} title="Logging Using your sim" onPress={this._onPressButton} />
<Text> {this.state.contacts} </Text>
</View>
// <View>
//
// </View>
)
}
}
export default Login
我将位置保存在 BackgroundGeolocation.getCurrentLocation(lastLocation => 方法
当我刷新页面时,它会移动到启动屏幕,然后进入login.js屏幕
,它将当前位置保存到Firebase。
由于代码位于登录页面上,因此仅当打开应用程序并重定向到登录页面时,我才面临被调用的问题。
我找不到我应该在哪里写代码,以便即使应用程序关闭也无法发送代码。由于这是我在react nativr中的第一个程序,因此无法获得此
我正在使用android模拟器进行检查。 我的问题是,我应该在哪里保留这种后台记录方法,以使其在后台跟踪位置并在更改后保存到Firebase。 我是否正在以正确的方法将位置保存在Firebase中?
很抱歉使问题复杂化,但作为入门者,对于流程确实感到困惑
谢谢
答案 0 :(得分:1)
据我了解,即使关闭应用程序,您也想跟踪位置。在这种情况下,您可以使用此库 https://github.com/jamesisaac/react-native-background-task
答案 1 :(得分:1)
您当前的代码仅请求一次位置更新-当代码被称为BackgroundGeolocation.getCurrentLocation
时-如果我正确阅读了本机模块,则应调用BackgroundGeolocation.start()
来启动服务以获取递归的位置更新,即使应用在后台运行。
(来源:您使用的模块的打字稿文档:https://github.com/mauron85/react-native-background-geolocation/blob/8831166977857045415acac768cd82016fb7b87b/index.d.ts#L506)