简体   繁体   中英

android app stop variable from resetting - lifecycle

I have an app that has a few screens. The Main screen automatically opens a "new" screen if it's the first time the user opens the app. I then set a boolean variable (on the Main screen) keeping track of this.

The intention is if the user goes back to the Main screen, the code that opens the "new" screen can be skipped.

The problem is that the variable keeps getting reset on OnCreate. So, I added some code to use SharedPreferences.

This works; however, I want to clear the variable when the app exits. (I want the "new" screen to open every time the app opens the first time). So, looking at the lifecycle I tried both onStop and onDestory. The SharedPreferences are cleared but... not when the app is exited; but when the "new" screen appears.

Am I looking at the lifecycle wrong? Is there some sort of global variable I can declare that only lives while the app is open?

This functionality is the requirement, so I cannot change it.

You should use onSaveInstanceState and onRestoreInstanceState, they will keep the boolean alive if your activity calls onCreate but not if you exit and come back later.

See this answer for implementation: Saving Android Activity state using Save Instance State

您可以在整个代码的第一行定义变量,这样它只会在再次打开应用程序时重置。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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