Android 异步存储&x2B;firebase读取数据挂起应用程序

Android 异步存储&x2B;firebase读取数据挂起应用程序,android,firebase,react-native,Android,Firebase,React Native,当设备连接到internet时,我正在使用firebase上编写的React native AsyncStroare 但我面临着一个未知的问题,即挂起我的应用程序,它甚至不允许单击事件 有人曾经面对过这样的问题吗 我在分享代码 import React, { Component, PropTypes } from 'react'; import { StyleSheet, View, Text, Dimensions, AppRegistry, TouchableOpacity, Animate

当设备连接到internet时,我正在使用firebase上编写的React native AsyncStroare 但我面临着一个未知的问题,即挂起我的应用程序,它甚至不允许单击事件

有人曾经面对过这样的问题吗

我在分享代码

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',
  },
});
import React,{Component,PropTypes}来自'React';
从“react native”导入{样式表、视图、文本、尺寸、AppRegistry、TouchableOpacity、动画、按钮、警报、振动、异步存储、NetInfo};
从“react-native-mauron85-background-geolocation”导入BackgroundGeolocation;
从“react native maps”导入MapView,{MAP_TYPES};
从“firebase”导入*作为firebase;
const onStartPress=()=>{
BackgroundGeolocation.start(
功能(位置){
Alert.Alert('跟踪已启动');
振动;
}
);
};
const onStopPress=()=>{
背景地理定位(
功能(位置){
警报。警报(“跟踪已停止”);
振动;
}
);  
};
//初始化Firebase
常量firebaseConfig={
apiKey:“xxxx”,
authDomain:“first-project-910a2.firebaseapp.com”,
数据库URL:“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');
常量电子邮件=”test@email.com";
const password=“test121”;
var-uid=0;
var currentDistance=0;
var EventOccurse=0;
firebaseApp.auth().signInWithEmailAndPassword(电子邮件,密码).catch(函数(错误){
var errorCode=error.code;
var errorMessage=error.message;
日志(错误代码+”:“+错误消息);
});
firebase.auth().onAuthStateChanged(函数(用户){
如果(用户){
uid=JSON.stringify(user.uid);
}否则{
uid=0;
}  
});
var SchoolJS=require('./SchoolJS.js');
const{width,height}=Dimensions.get('window');
常量纵横比=宽度/高度;
常数纬度=23.0123937;
常数经度=72.5227731;
常数纬度δ=0.0922;
常数经度_δ=纬度_δ*纵横比;
设id=0;
设arb=0.01;
设busGpsCoordinates=[];
设prevlatOffline=0;
设prevlongOffline=0;
导出默认类MyScene扩展组件{
建造师(道具){
超级(道具);
此.state={
地区:{
纬度:纬度,
经度:经度,
纬度三角洲:纬度三角洲,
经度三角洲:经度三角洲,
},
};
}
组件willmount(){
BackgroundGeolocation.configure({
期望准确度:10,
静止半径:50,
距离过滤器:50,
位置超时:30,
通知标题:“背景跟踪”,
notificationText:“已启用”,
调试:错误,
startOnBoot:错,
stopOnTerminate:false,
locationProvider:BackgroundGeolocation.provider.ANDROID\u活动\u提供程序,
间隔时间:5000,
快速区间:2000年,
活动间隔:5000,
stopOnStillActivity:false,
});    
背景地理位置。关于('location',(location)=>{
//因为我可以从多个设备或浏览器选项卡进行连接,所以我们分别存储每个连接实例
//每当connectionsRef的值为null(即没有子项)时,我都处于脱机状态
var myConnectionsRef=firebase.database().ref('users/'+uid+'/connections');
//存储上次断开连接的时间戳(上次看到我在线时)
var lastOnlineRef=firebase.database().ref('users/'+uid+'/lastOnline');
var connectedRef=firebase.database().ref('.info/connected');
connectedRef.on('value',函数(snap){
if(snap.val()==真){
//我们已连接(或重新连接)!请在此处执行仅在联机(或重新连接)时才应执行的任何操作
//将此设备添加到我的连接列表
//此值可能包含有关设备的信息或时间戳
var con=myConnectionsRef.push(真);
//断开连接后,请卸下此设备
con.onDisconnect().remove();
//当我断开连接时,请更新上次看到我在线的时间
lastOnlineRef.onDisconnect().set(firebase.database.ServerValue.TIMESTAMP);
//重新连接时与firebase同步
/*背景地理定位。开始(()=>{
log(“[DEBUG]BackgroundGeolocation启动成功”);
});*/
AsyncStorage.getItem(uid+“脱机”)。然后((值)=>{
busGpsJsonObj=JSON.parse(值);
日志(“总线对象:+busGpsJsonObj”);
if(busGpsJsonObj!=null){
busGpsJsonObj.forEach(功能(位置OBJ){
newPostKey=firebase.database().ref().child('gps').push().key;
todaydate=SchoolJS.today();
newPostKey=(newPostKey!=“”)吗?“/”+todaydate+“/”+newPostKey:”;
firebaseApp.database().ref('gps/'+uid+newPostKey).设置({
速度:位置目标速度,
准确度:定位目标准确度,
轴承:位置OBJ.轴承,
经度:locationObj.经度,
高度:位置OBJ高度,
纬度:位置OBJ.纬度,
时间:locationObj.time,
locationProvider:locationObj.locationProvider,
});
});     
AsyncStorage.removietem(uid+“脱机”);
busGpsCoordinates=[];
}      
}).完成();
}      
});
//在这里处理您的位置
timekey=JSON.stringify(location.time);
speed=JSON.stringify(location.speed),
精度=JSON.stringify(location.accurity),
bearing=JSON.stringify(location.bearing),