Written an application for android on java, it should not be closed. Now we tested on Android 6.0 Marshmallow by rolling up the application, after a while, using other applications, click on the shortcut of our application and it opens in the same Activity as it was but with empty static variables. Is it possible to protect static variables from system cleaning?
2 answers
No, static variables can not be protected from cleaning by the system - you can not really influence the garbage collection process. But in general, the lifetime of static variables is tied to the lifetime of the application, so it is better not to use static variables in the Activity :
The lifetime of static variables is tied to the lifetime of the application and, accordingly, the memory from under them is released when the virtual machine rolls out your application from memory, and if, for example, the service is running, then it may not happen soon, the variables will hang and memory.
It is better to save the VALUES (which you now store in these variables) somewhere for long-term storage — for example, in a database, in a file either in SharedPreferecnes , or as an option to save in the Bundle in the onSaveInstanceState method.
PS And the fact that you have the "Activate, which was, but with empty static variables" is most likely due to the fact that somewhere these variables are still cleared in the application.
- Static variables in the
Applicationclass work just like theActivityclass. As in any other class. Therefore, they are static (they belong not to the class object, but to the class itself). If it simply dies activations (for example, calledfinish()), then its static variable will not be cleared. If the entire application process dies, then no static will survive. - eugeneek - @eugeneek, yes, you are right, about the fact that static variables during the re-creation of Activiti will be cleared - I wrote this incorrectly. Changed the answer) - Ksenia
Why will not work as you describe - answered here.
In order to see your data again you need to save it in the onPause method, override this method in your Activity . Then, to save your values, you can use one of the following methods:
- Shared Preferences
- Files
- Databases
- Content Providers
I also recommend reading the official documentation, in which there are examples and a more accurate description. Link to off. documentation: Storage Options
SharedPreferecnesand write a lot to the database and get the values ​​from there. - McDaggen