Search code examples
androidandroid-4.2-jelly-bean

Android Activity Lifecycle versus Process Lifecycle


After using the NDK for almost a year I've come to realize that the Process lifecycle in Android is different than the Activity lifecycle.

More specifically, my native library is being loaded in OnCreate but in onDestroy it is not unloaded (I don't even know if you can unload a native library here), but at the next OnCreate, it is still the same process, so all global variables from my native library are still alive with their state preserved. This is the same for static variables in Java as well.

This was pretty fine with Android 2.3 but I recently got onto Android 4.2.2 and I noticed something really weird. It is possible now to have the process killed and the activity to just call onRestart() (or that is what I assume from reading the logs) which is kind of weird to be honest because I assume onCreate would be called right after the process is instantiated, but he keeps a different tab because he thinks in "activities" and not processes. So basically if I pause one of my apps for a really long time (say 1+ hours) and I return to it, it usually results in a crash.

Excerpt from the device log :

04-14 04:41:34.886  2376  2376 I am_on_paused_called: [0,com.re3.benchmark.AboutActivity]
04-14 05:06:26.128   386   594 I am_proc_died: [0,2376,com.re3.benchmark]
04-14 13:19:44.256   386   538 I am_proc_start:[0,4761,10062,com.re3.benchmark,activity,com.re3.benchmark/.AboutActivity]
04-14 13:19:44.295   386   595 I am_proc_bound: [0,4761,com.re3.benchmark]
04-14 13:19:44.397   386   595 I configuration_changed: 5248
04-14 13:19:44.459   386   595 I am_restart_activity: [0,1115347592,8,com.re3.benchmark/.AboutActivity]
04-14 13:19:44.701  4761  4761 I am_on_resume_called: [0,com.re3.benchmark.AboutActivity]
04-14 13:19:44.881   386   401 I am_activity_launch_time: [0,1115347592,com.re3.benchmark/.AboutActivity,631,631]
04-14 13:19:52.725   386   595 I am_crash: [4761,0,com.re3.benchmark,8961606,java.lang.NullPointerException,NULL,REFramework.java,330]
04-14 13:19:52.725   386   595 I am_finish_activity: [0,1115347592,8,com.re3.benchmark/.AboutActivity,crashed]
04-14 13:19:52.772   386   595 I am_pause_activity: [0,1115347592,com.re3.benchmark/.AboutActivity]

PS:I do realize the crash originates in my code, but my code doesn't really handle onRestart being the first function to be called in the entire process (as in, it bypasses my native library initializations since I expect onCreate to be called first ).


Solution

  • You probably should be loading native lib in Application.onCreate and not Activity.

    If you have more than 1 Activity, only the currently visible is created and if you were loading lib in the first Activity, you won't get it loaded at this point.