0

I know how to save and restore an application with OnPause and OnResume. I did when the user press the back button, when he turn the tablet and when he press the home button. But my problem is I don't know how to do the same when the user turn off the application.

So I would like to know how to restore my app at the same state, it was when the user turn off the app? At what moment I save the state?

Thank you very much for your help !

2 Answers2

0

The simplest data storage you can use is SharedPreferences.

Some examples you can find here:

https://developer.android.com/guide/topics/data/data-storage.html#pref

Android Shared preferences example

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Bogdan Ustyak
  • 5,639
  • 2
  • 21
  • 16
  • Thank you for your answer ! Are you sure I can turn off the application or the mobile and find back my same state with SharedPreferences ? – ValentinLoricourt Apr 28 '16 at 22:11
  • Yes, I'm totally sure. This data will persist across user sessions (even if your application is killed). – Bogdan Ustyak Apr 28 '16 at 22:13
  • Ok I will try this way. Can you just tell me why should I use SharedPreferences and not onDestroy(from the other answer): I don't see differences... (There is a lot of way to do, I had already eliminate onsavedinstance because I have a lot of data but I discover two more methods now) – ValentinLoricourt Apr 28 '16 at 22:19
  • onResume, OnPause, onDestroy, onsavedinstance are just a methods of activity lifecycle. So you can use these methods while you activity is in memory. As soon as your app will be killed and you activity will be finished all data will be lost. So you need some storage to dave data. SharedPreferences is just a one. – Bogdan Ustyak Apr 28 '16 at 22:23
0

Android Activity calls onDestroy() method before just before it gets destroyed. You can implement your logic of saving a state there. Check Activity Lifecycle to know more. http://developer.android.com/training/basics/activity-lifecycle/index.html

Anurag
  • 156
  • 12
  • Thank you. I saw this method somewhere but my problem was I don't know how to restore the state(saved by onDestroy)? And I just duplicate my code to save from OnPause to onDestroy: there is nothing more to do to save the state? – ValentinLoricourt Apr 28 '16 at 22:17
  • You can mark your class Serializable and then use java's serialization technique to save and retrieve the sate of an object. – Anurag Apr 28 '16 at 22:22
  • I don't know this, I will learn about serialization. Thank you for your help ! – ValentinLoricourt Apr 28 '16 at 22:28
  • Bogdan Ustyak is right. onDestroy() method just notifies you that the activity is being destroyed. You will need to use either SharedPreferences or java's serialization to save the state of an object. – Anurag Apr 28 '16 at 22:28