Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use onTerminate() method , android?

Tags:

android

I am trying to save some variables using SharedPreferences. In my onCreate() method I initialize my variables using SharedPreferences , and I want when the application ends to store this variables. I am putting this code on the onTerminate() method but the variables are never stored. I think that the onTerminate() method is never called , as i also see a comment on this method saying // not guaranteed to be called . So how can i save the state of my variable just before I stop the application? I know how , I just don't know where to place my code.

like image 415
donparalias Avatar asked Jun 08 '12 12:06

donparalias


3 Answers

Actually, to be safe, you should save things in onPause() because (at least pre-3.0) your process can be killed by the OS after it calls onPause(). This implies that onStop() and onDestroy() may or may not be called.

In any case, there is no guarantee that onDestroy() will ever be called. If the OS decides to kill your process it won't bother calling onDestroy() on any activities.

like image 151
David Wasser Avatar answered Oct 11 '22 05:10

David Wasser


and i want when the application ends to store this variables.

That will not work, because you do not get control when "the application ends".

Either:

  • save the data when the data changes, or

  • save the data when the user tells you (e.g., via some sort of Save action bar item), or

  • save the data when onPause() of the activity where you modified the data is called

like image 5
CommonsWare Avatar answered Oct 11 '22 03:10

CommonsWare


You shouldn't use this function.

This method is for use in emulated process environments. It will never be called on a production Android device, where processes are removed by simply killing them; no user code (including this callback) is executed when doing so.

Source

like image 5
RyPope Avatar answered Oct 11 '22 05:10

RyPope