AsyncStorage getItem和setItem在Android设备中不起作用

时间:2019-05-30 04:41:23

标签: react-native react-native-android asyncstorage

我试图将当前日期的值(以毫秒为单位)存储在AsyncStorage setItem中,并在应用程序状态更改时使用getItem检索它。我正在使用AppState侦听器更改状态并比较值。当我在ios模拟器上运行它时,它工作正常,但当我在android设备上运行时,则不起作用。有人可以帮我吗?

    StoreDate = async () => {

        console.log("Date",new Date().getTime().toString());
        await AsyncStorage.setItem('date', new Date().getTime().toString());
      };

      retrieveDate = async () => 
      {
        try{
        let value = await AsyncStorage.getItem('date')
         var Intvalue = parseInt(value,10); // value of newDate().getTime() as Integer
         console.log("Intvalue",Intvalue);
        console.log("value",value);
        Alert.alert(value);
        return value;
    }
          catch(error){
            Alert.alert(error);
          }
      };

    _handleAppStateChange = (nextAppState) => 
         if (this.state.appState.match(/inactive/) && nextAppState === 'background') {

          let getDateTime = this.StoreDate().then((filter) => {
            console.log("filter",filter);
            console.log("getDateTime",getDateTime);
          });
      }
  else if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {

let currentDate = new Date().getTime();   
          let currentDateTimeStamp =   Math.floor(currentDate / 1000);

           console.log("currentDate",currentDate);
           console.log("currentDateTimeStamp",currentDateTimeStamp);




          let storedTime = this.retrieveDate().then((filter)=>  {

            console.log("filter",filter);
            console.log("storedTime",storedTime);

            var Intfilter = parseInt(filter,10);
            console.log("Intfilter",Intfilter);


            var IntfilterSeconds = Math.floor(Intfilter / 1000);
            console.log("IntfilterSeconds",IntfilterSeconds);

             var timeDiff = currentDateTimeStamp - IntfilterSeconds;
            console.log("timeDiff",timeDiff)



            if(timeDiff > 300){
              ** DO Something ** 

              })



             }
            else{
          **   Do Something **
              })

           }

           });

        }

1 个答案:

答案 0 :(得分:0)

有解决此问题的方法。 我发现这不是AsyncStorage的问题,而是AppState。 android中主要有两个appstate:Active和Background。 当应用程序在后台匹配(active | background)&& nextAppState ='background'时处理appState确实为我解决了这个问题。