I am wondering: when an app is to be killed, does Android wait for the currently running function to return, or does Android stop it before it ends by itself?
Your app may be killed by the system at any time without another line of its code being executed. According to the documentation however, there are a few methods which are not "killable":
As onDestroy() won't get called for sure, it is more save to use the onPause() Method to write any persistent data to storage:
protected void onPause(){
super.onPause();
if(isFinishing()){
// store data
}
}
It would make sense that it would kill a method mid-execution. Consider that many "hangs" are due to an infinite loop condition within a single method's loop. How else would an OS kill such an app without killing it in the middle of executing a method?
Also consider this: Even if an OS allowed the "current" method to finish executing before killing the app, and then killed the app, it would then be killing the app in the middle of the method that had called the first method that the OS allowed to continue executing until it finished. OK, so then continue this thinking to its extreme. If the OS allowed each function that was in the middle of executing to finish before killing the app, then the end result is that the OS allows the entire app to run to completion, which is exactly what killing an app is supposed to circumvent. Thus, an OS, when killing an app, must terminate it in the middle of "a"... acutally "many".... functions. Every function that's on the callstack does NOT get a chance to finish!
Each android app runs on a separate Dalvik VM. and when android kills that app , it destroys that VM instance. and doesn't care for the threads you are using or what are they doing , you can easily test that , by creating a tcp server socket which will block until a client connects and then kill the app, nothing happens, no interrupt exception raise or anything because the VM instance itself get killed.
The OS kills the JVM process, with all the "functions" in all the threads. In practical terms, you shouldn't assume that a method is a transaction. Instead, one should assume it can be terminated at any time and design appropriately.
Android can kill your app at any time, at any point. But android tries to keep your app running if he has enought resources for it or if you have foreground activity or service.
Before killing your app android will call lifecycle methods of your components according SDK documention. Not all lifecycle methods are guaranteed to be called.
It really depends on the method of killing. Killing due to crash? All threads are stopped where ever they are. Killing due to watchdog timer? All thread killed wherever they are. Killed due to closing the activity by user? Activities/threads will finish what they're doing. Basically, you can't count on it, but it may happen. If you're worried about data corruption due to closing, you need to use a transactional model.