当设备与互联网连接时,我使用React本机AsyncStroare并写在firebase上 但是我面临着一个未知的问题,它挂断了我的应用程序,它甚至不允许点击事件
有人曾经遇到过这种问题吗?
我分享代码,
import React, { Component, PropTypes } from 'react';
import { StyleSheet, View, Text, Dimensions, AppRegistry, TouchableOpacity, Animated, Button, Alert, Vibration, AsyncStorage, NetInfo} from 'react-native';
import BackgroundGeolocation from 'react-native-mauron85-background-geolocation';
import MapView, { MAP_TYPES } from 'react-native-maps';
import * as firebase from "firebase";
const onStartPress = () => {
BackgroundGeolocation.start(
function (locations) {
Alert.alert('Tracking has been started');
Vibration.vibrate();
}
);
};
const onStopPress = () => {
BackgroundGeolocation.stop(
function (locations) {
Alert.alert('Tracking has been stop');
Vibration.vibrate();
}
);
};
// Initialize Firebase
const firebaseConfig = {
apiKey: "xxxx",
authDomain: "first-project-910a2.firebaseapp.com",
databaseURL: "https://first-project-910a2.firebaseio.com",
storageBucket: "gs://first-project-910a2.appspot.com",
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const rootRef = firebase.database().ref();
const itemsRef = rootRef.child('gps');
const email = "test@email.com";
const password = "test121";
var uid = 0;
var currentDistance = 0;
var eventOccur = 0;
firebaseApp.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
console.log( errorCode + ": "+ errorMessage );
});
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
uid = JSON.stringify(user.uid);
} else {
uid = 0;
}
});
var SchoolJS = require('./SchoolJS.js');
const { width, height } = Dimensions.get('window');
const ASPECT_RATIO = width / height;
const LATITUDE = 23.0123937;
const LONGITUDE = 72.5227731;
const LATITUDE_DELTA = 0.0922;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
let id = 0;
let arb = 0.01;
let busGpsCoordinates = [];
let prevlatOffline = 0;
let prevlongOffline = 0;
export default class MyScene extends Component {
constructor(props) {
super(props);
this.state = {
region: {
latitude: LATITUDE,
longitude: LONGITUDE,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
},
};
}
componentWillMount() {
BackgroundGeolocation.configure({
desiredAccuracy: 10,
stationaryRadius: 50,
distanceFilter: 50,
locationTimeout: 30,
notificationTitle: 'Background tracking',
notificationText: 'enabled',
debug: false,
startOnBoot: false,
stopOnTerminate: false,
locationProvider: BackgroundGeolocation.provider.ANDROID_ACTIVITY_PROVIDER,
interval: 5000,
fastestInterval: 2000,
activitiesInterval: 5000,
stopOnStillActivity: false,
});
BackgroundGeolocation.on('location', (location) => {
// since I can connect from multiple devices or browser tabs, we store each connection instance separately
// any time that connectionsRef's value is null (i.e. has no children) I am offline
var myConnectionsRef = firebase.database().ref('users/'+uid+'/connections');
// stores the timestamp of my last disconnect (the last time I was seen online)
var lastOnlineRef = firebase.database().ref('users/'+uid+'/lastOnline');
var connectedRef = firebase.database().ref('.info/connected');
connectedRef.on('value', function(snap) {
if (snap.val() === true) {
// We're connected (or reconnected)! Do anything here that should happen only if online (or on reconnect)
// add this device to my connections list
// this value could contain info about the device or a timestamp too
var con = myConnectionsRef.push(true);
// when I disconnect, remove this device
con.onDisconnect().remove();
// when I disconnect, update the last time I was seen online
lastOnlineRef.onDisconnect().set(firebase.database.ServerValue.TIMESTAMP);
//sync with firebase when reconnect
/*BackgroundGeolocation.start(() => {
console.log('[DEBUG] BackgroundGeolocation start successfully');
});*/
AsyncStorage.getItem(uid+"offline").then((value) => {
busGpsJsonObj = JSON.parse(value);
console.log("BUS OBJ : " + busGpsJsonObj);
if(busGpsJsonObj != null){
busGpsJsonObj.forEach(function(locationObj) {
newPostKey = firebase.database().ref().child('gps').push().key;
todaydate = SchoolJS.today();
newPostKey = (newPostKey != "") ? "/"+todaydate+"/"+newPostKey : "";
firebaseApp.database().ref('gps/' + uid+newPostKey).set({
speed : locationObj.speed,
accuracy: locationObj.accuracy,
bearing: locationObj.bearing,
longitude: locationObj.longitude,
altitude: locationObj.altitude,
latitude: locationObj.latitude,
time: locationObj.time,
locationProvider: locationObj.locationProvider,
});
});
AsyncStorage.removeItem(uid+"offline");
busGpsCoordinates = [];
}
}).done();
}
});
//handle your locations here
timekey = JSON.stringify(location.time);
speed = JSON.stringify(location.speed),
accuracy = JSON.stringify(location.accuracy),
bearing = JSON.stringify(location.bearing),
longitude = JSON.stringify(location.longitude),
altitude = JSON.stringify(location.altitude),
latitude = JSON.stringify(location.latitude),
time = JSON.stringify(location.time),
locationProvider = JSON.stringify(location.locationProvider),
timekey = timekey.toString();
newPostKey = firebase.database().ref().child('gps').push().key;
todaydate = SchoolJS.today();
newPostKey = (newPostKey != "") ? "/"+todaydate+"/"+newPostKey : "";
latitude = latitude.replace(/^"(.*)"$/, '$1');
longitude = longitude.replace(/^"(.*)"$/, '$1');
NetInfo.isConnected.fetch().then(isConnected => {
if(!isConnected)
{
if(busGpsCoordinates.length == 0)
{
busGpsCoordinates.push({
speed : speed,
accuracy: accuracy,
bearing: bearing,
longitude: longitude,
altitude: altitude,
latitude: latitude,
time: time,
locationProvider: locationProvider,
});
AsyncStorage.setItem(uid+"offline", JSON.stringify(busGpsCoordinates ) );
}
else
{
prevData = JSON.stringify(busGpsCoordinates[busGpsCoordinates.length - 1] );
prevData = JSON.parse(prevData);
currentDistance = SchoolJS.distance(prevData.latitude,prevData.longitude,latitude,longitude);
if(currentDistance > 30)
{
busGpsCoordinates.push({
speed : speed,
accuracy: accuracy,
bearing: bearing,
longitude: longitude,
altitude: altitude,
latitude: latitude,
time: time,
locationProvider: locationProvider,
});
AsyncStorage.setItem(uid+"offline", JSON.stringify(busGpsCoordinates ) );
}
}
}
});
this.animateRandom(parseFloat(latitude),parseFloat(longitude));
// retrieve the last record from `ref`
if(uid != 0)
{
itemsRef.once("value", function(snapshot) {
var totalChild = snapshot.child(uid).child(todaydate).numChildren();
if(totalChild == 0)
{
firebaseApp.database().ref('gps/' + uid+newPostKey).set({
speed : speed,
accuracy: accuracy,
bearing: bearing,
longitude: longitude,
altitude: altitude,
latitude: latitude,
time: time,
locationProvider: locationProvider,
});
}
});
itemsRef.child(uid).child(todaydate).limitToLast(1).on('child_added', function(snapshot) {
previousLatitude = JSON.stringify(snapshot.val().latitude);
previousLongitude = JSON.stringify(snapshot.val().longitude);
previousLatitude = previousLatitude.replace(/^"(.*)"$/, '$1');
previousLongitude = previousLongitude.replace(/^"(.*)"$/, '$1');
latitude = latitude.replace(/^"(.*)"$/, '$1');
longitude = longitude.replace(/^"(.*)"$/, '$1');
currentDistance = SchoolJS.distance(previousLatitude,previousLongitude,latitude,longitude);
eventOccur++;
if(currentDistance > 30)
{
firebaseApp.database().ref('gps/' + uid+newPostKey).set({
speed : speed,
accuracy: accuracy,
bearing: bearing,
longitude: longitude,
altitude: altitude,
latitude: latitude,
time: time,
locationProvider: locationProvider,
});
}
});
}
});
BackgroundGeolocation.on('stationary', (stationaryLocation) => {
//handle stationary locations here
console.log(JSON.stringify(stationaryLocation));
});
BackgroundGeolocation.on('error', (error) => {
console.log('[ERROR] BackgroundGeolocation error:', error);
});
BackgroundGeolocation.isLocationEnabled((success, fail) => {
if(success != 1 && fail == "undefined")
{
BackgroundGeolocation.stop(() => {
console.log('[DEBUG] BackgroundGeolocation stop successfully');
});
}
});
}
onRegionChange(region) {
this.setState({ region });
}
jumpRandom() {
this.setState({ region: this.randomRegion() });
}
animateRandom(newLatitude = LATITUDE ,newLongitude = LONGITUDE) {
this.map.animateToRegion(this.randomRegion(newLatitude, newLongitude));
}
randomRegion(newLatitude = LATITUDE ,newLongitude = LONGITUDE) {
const { region } = this.state;
return {
...this.state.region,
latitude: newLatitude,
longitude: newLongitude,
};
}
render() {
return (
<View style={styles.container}>
<MapView
showsUserLocation = { true }
provider={this.props.provider}
ref={ref => { this.map = ref; }}
mapType={MAP_TYPES.TERRAIN}
style={styles.map}
initialRegion={this.state.region}
onRegionChange={region => this.onRegionChange(region)}
>
<MapView.Marker.Animated
coordinate={this.state.region}
/>
</MapView>
<View style={styles.buttonContainer}>
<TouchableOpacity
onPress={onStartPress}
style={[styles.bubble, styles.button]}
>
<Text>Start</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={onStopPress}
style={[styles.bubble, styles.button]}
>
<Text>Stop</Text>
</TouchableOpacity>
</View>
</View>
)
}
}
MyScene.propTypes = {
provider: MapView.ProviderPropType,
};
const styles = StyleSheet.create({
container: {
...StyleSheet.absoluteFillObject,
justifyContent: 'flex-end',
alignItems: 'center',
},
map: {
...StyleSheet.absoluteFillObject,
},
bubble: {
backgroundColor: 'rgba(255,255,255,0.7)',
paddingHorizontal: 18,
paddingVertical: 12,
borderRadius: 20,
},
latlng: {
width: 200,
alignItems: 'stretch',
},
button: {
width: 80,
paddingHorizontal: 12,
alignItems: 'center',
marginHorizontal: 10,
},
buttonContainer: {
flexDirection: 'row',
marginVertical: 20,
backgroundColor: 'transparent',
},
});
任何人都可以帮助我摆脱这个问题。