Is it safe to use static class variables in an android application

后端 未结 4 962
遇见更好的自我
遇见更好的自我 2021-01-19 01:52

I am aware of the technique of extending the Application class to provide global storage. However in my case I am writing a class for a library function, so do not wish to f

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-19 02:51

    I'm a little confused about what you're trying to do. You're trying to create a utility library in Java to be used by other applications? You're trying to create a whole Activity intended for use by other applications?

    At any rate, as other posters have mentioned, applications can be killed at almost any time when resources become tight. There's simply no way to guarantee that static global values will remain resident in memory. You must provide a way to back it up on onPause() or onSaveInstanceState().

    If you're writing a utility library, I presume that it returns some master object which holds all of its state. Add saveState(Bundle), restoreState(Bundle) methods to that object, and optionally saveToSharedPreferences() and restoreFromSharedPreferences() methods as well.

    If it's an Activity you're writing, you're probably already familiar with the ways of saving state.

    Me, I'm fond of combining the "singleton pattern" with shared preferences: https://stackoverflow.com/a/13673178/338479

提交回复
热议问题