简体   繁体   English

如何检查是否正在打开应用-Android Studio

[英]How to check if an app is being opened - Android Studio

I'm making a game and am saving data for the player using sharedPreferences. 我正在制作游戏,并正在使用sharedPreferences为玩家保存数据。 The way I have it set up right now, every time the main application (the first page) is loaded, the old data it held before is loaded. 我现在设置的方式是,每次加载主应用程序(第一页)时,都会加载之前保存的旧数据。 So, imagine a player has 100$, and they exit the app. 因此,假设一个玩家有100美元,然后他们退出了该应用程序。 Upon opening the app again, this data will be loaded and everything seems fine. 再次打开该应用程序后,将加载此数据,并且一切正常。

The problem, however, is that if a player's money is changed in ANOTHER activity, the way I have it set up right now is that any time a player navigates back to the main activity, the data is loaded. 但是,问题在于,如果在另一个活动中更改了玩家的资金,则我现在设置的方式是,只要玩家每次导航回到主要活动,就会加载数据。 So if the player has $100 on the main activity, this info is saved every few seconds on the main activity. 因此,如果玩家在主要活动中有$ 100,则此信息每隔几秒钟保存一次。 If the player spends 50$ on a second activity, when they return to the main activity, since the last saved data the main activity has is $100, it will load the $100. 如果玩家在第二项活动上花费50美元,则当他们返回主活动时,由于主活动最后一次保存的数据为$ 100,因此它将加载$ 100。

This is a problem, and a way to fix it is to ONLY LOAD THE DATA WHEN THE APP IS OPENED. 这是一个问题,解决此问题的方法是仅在打开应用程序时加载数据。 So like I don't want to load the data every time the player navigates to the main activity, but only when they open the app. 因此,就像我不想每次播放器导航到主要活动时(仅在他们打开应用程序时)加载数据一样。 I need a simple if() boolean statement to do this, but I'm not sure what the statement I need is. 我需要一个简单的if()布尔语句来执行此操作,但是我不确定我需要的语句是什么。

Thanks! 谢谢!

Store a boolean in sharedPreferences and check if it exists or if it's false/true in the create of the activity, such as storing a value for "hasLoaded" with a value of either true or false . 将布尔值存储在sharedPreferences并检查其是否存在或在活动创建中是否为false / true,例如,将"hasLoaded"的值存储为truefalse check this value in onCreate and then do your logic accordingly. onCreate检查此值,然后相应地执行逻辑。

OR alternatively, 或者,

create a static variable in your mainActivity for hasLoaded , then in onCreate, do everything you want to do and then change it to true. 在mainActivity中为hasLoaded创建一个静态变量,然后在onCreate中,执行您想做的所有事情,然后将其更改为true。

static boolean hasLoaded = false;

if(!hasLoaded){
//all your logic here
hasLoaded = true;
}

note: storing it in sharedPrefs will ensure that your initialization will only happen ONCE for all usages of the app, while storing it in a static variable will make sure it only happens once PER RUN of the app 注意:将其存储在sharedPrefs中将确保您的初始化仅对应用程序的所有使用一次发生,而将其存储在静态变量中将确保仅在应用程序每次运行时发生一次

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM