Losing reference to static data in Android Studio

試著忘記壹切 提交于 2019-12-24 00:42:51

问题


I'm having issues with instances of static data being lost when my app goes into the background, causing null pointer exception errors.

The static data is very context or 'state' dependant, and can't be generated generically on initialisation.

To ensure I keep hold of this data, will I be force to write the data to storage or this there some other way of ensuring my static data isn't lost when the app is put into the background?


回答1:


Static fields are part of the class, not an object. When Android recycles memory, the static fields will be recycled as well and you will lose all data held in them. Remember that the OS can, at any point, reclaim memory for your application when it's in the background.

If you have state that you wish to preserve, you will need to persist it to disk, on Android, relying on anything that's kept in memory in the background is a risky strategy.

I'd use shared preferences for this, but you could also use a serialized file stream if you wanted to. Shared preferences are just easier and well-documented.

In your onResume() methods, you'd read back the values and you'd of course persist them in onPause(). This will also allow you to handle situations where, for example, a phone call comes in or where the user switches to a different app, even for just a moment.




回答2:


When your app is in the background and the OS decides that it wants to reclaim memory, it might kill the process. In this case, when you return to the app, the process gets recreated and your static variables will be uninitialized.

If you want to keep important stuff, put them in SharedPreferences, a database, or serialize them into a file, depending on your needs.



来源:https://stackoverflow.com/questions/37701197/losing-reference-to-static-data-in-android-studio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!