Public static variables and Android activity life cycle management

后端 未结 3 1383
無奈伤痛
無奈伤痛 2020-12-03 02:48

According to the documentation the Android OS can kill the activity at the rear of the backstack.

So, say for example I have an app and open the Main Activity (let\

3条回答
  •  暖寄归人
    2020-12-03 03:36

    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.

提交回复
热议问题