Public static variables and Android activity life cycle management

前提是你 提交于 2019-11-27 13:31:28

If the process is killed then all static variables will be reinitialized to their default values.

So whatever value you have set in Activity A will not persist

Good explanation can be viewed here from 2:50 http://www.infoq.com/presentations/Android-Design

Here are some instructions for those who want to test this issue manually: Create android v.4 emulator, then go to settings -> developer settings -> disable background tasks. Then create sample android project with 2 activities, declare static variable in activity A, initialize it in onCreate() method. Place a button in activity A that starts activity B. In Activity B's onCreate() method print the value of A.staticVar to logcat.

Launch the project - activity A appears. Hit the button - activity B appears, value of static variable is printed to logcat. Press the home button and launch any other program - your sample project process will be killed (because you have disabled background processes). Now long-press on home button - you will see the list of recently launched programs. Select your sample project - OS will try to recover your project's activities back-stack and recreate last running activity B. But at this step program will crash with NullPointerException because A.staticVar will be null, and we are trying to print it to logcat.

The answer is (3). If you need to keep values, persist them in shared preferences when each activity pauses and restore them when it resumes. Alternatively, you can also maintain an "initialized" static flag and re-initialize the static variables from any activity's onCreate() method if it is false.

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