I'm trying to clear shared preferences when the user closes the app and only when he closes it. Using onDestroy() works only when the app is closed with the back press but not when the home button is pressed and app closed from recents. How can I do this?
-
2"I'm trying to clear shared preferences when the user closes the app" -- this makes no sense. If you do not want the data to be saved in a file, do not put it in a file in the first place. Just hold onto it in memory. There is no guarantee that `onDestroy()` of anything will be called before your process gets terminated -- removing a task from the overview screen is just one way that your process can get terminated. – CommonsWare Aug 10 '20 at 22:33
-
1Agree with @CommonsWare, don't rely on onDestroy() to clear preferences. Preferences are ideally used to keep the data persistent on the device till the user decides to clear it or if you have something like logout. If you can give some more specifics on the use case, it could help us answering. – pixelWorld Aug 11 '20 at 00:44
-
@pixelWorld I have a method which I want to call only once and never again as long as the user has the app opened. I store a boolean inside shared preferences which allows me to do just that and I clear it in onDestroy(). That way, shared preferences clear only when the whole app is closed by the back button. onStop() partially works like I want it to, it clears the preference on back pressed and when the app is closed from recents but it also clears when the activity is closed which I don't want. – A_Jayke Aug 11 '20 at 13:55
-
1You can try using activity isFinishing(), but again it won't always as onDestroy() is never guaranteed. https://stackoverflow.com/questions/5227071/understanding-of-isfinishing – pixelWorld Aug 11 '20 at 18:43
2 Answers
There is no guarantee that onDestroy will be called. I recommend reading about android activity lifecycle from a variety of sources. Android developer documentation does not provide all the details. Also Check out this question it might answer yours Which activity is called when app removed from recent list in android?
Look at this one for general understanding of lifecycle Android activity life cycle - what are all these methods for?
especially at https://stackoverflow.com/a/37753090/8720748

- 225
- 1
- 4
- 13
Instead of clearing the preferences in the activity from where I want it cleared, I created a class where I put methods setBoolean(), getBoolean(), clearPreference(), and added a SharedPreference editor to them. I call set boolean and get boolean inside my activity and in MainActivity, onStop(), I call clear preferences. That way it works when I close the app from recents.

- 153
- 1
- 12