Search code examples
androidandroid-activitysharedpreferencesondestroy

How to destroy activity when the app is closed from the recent menu?


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?


Solution

  • 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.