0

when the users logs-in a value pair is added to a SharedPreference. When the Apps gets killed, i want the user to be logged out and by the next start needs to login again. If the Users switches from one activity to another and back to the mainactivity again, he is logged out.

The problem is that the onStop from the MainActivity gets called and unsets the entry in the SharedPreference. I want the entry to stay when switching between Activities but get unset when the app gets exited/killed.

diadamalol
  • 198
  • 15

2 Answers2

2

Instead of onStop() try onDestroy(). onStop() is called when the activity is not visible, and onDestroy() when the activity is about to be destroyed.

mantlabs
  • 352
  • 2
  • 6
  • just be careful of rotation depending on your `Activity`'s settings as it can call `onDestory()` and create a new `Activity`. Might want to consider `android:configChanges="orientation"` – Jason Hu Mar 18 '16 at 21:02
  • I dont understand, why onDestroy doesnt get immediatly called, like the onStop does – diadamalol Mar 18 '16 at 21:06
  • When closing the app with the back arrow on the device the onDestroy gets immediatly called, but when you view all your open apps and swipe it to close, it does not get called – diadamalol Mar 18 '16 at 21:15
  • Maybe you should consider looking at this answer (about Home button) for exiting the App: http://stackoverflow.com/questions/6388351/how-to-finish-an-activity-when-home-button-pressed – mantlabs Mar 18 '16 at 21:19
1

The only guaranteed way of doing this that I've found is to create a class that implements Application.ActivityLifecycleCallbacks. Implement the necessary methods to keep counters of the activities that have been started, stopped, resumed, and destroyed.

Once you implement the class, you can register your implementation in your Application class implementation like this:

registerActivityLifecycleCallbacks(new MyLifecycleHandler());

When the number of started activities equals the number of destroyed activities, you can call your methods to log out the user. Or just keep a single counter and increment it as activities are started and decrement it once they are destroyed - same difference.

You can use this same strategy to tell whether your app is in the foreground or not.

SBerg413
  • 14,515
  • 6
  • 62
  • 88