Android Application class lifecyle documentation

半腔热情 提交于 2019-12-03 07:40:35

I can't find an official documentation telling me that yes, the Application class can be killed on low memory.

Below are the references to where it's been stated:

I can't find any official diagram representing the Application lifecycle neither.

This is a reasonable observation... Although the following is opinion-based, my best guess is that such a diagram would contradict the Android's multitasking "philosophy" as described in the last reference provided:

"A key to how Android handles applications in this way is that processes don't shut down cleanly. When the user leaves an application, its process is kept around in the background, allowing it to continue working (for example downloading web pages) if needed, and come immediately to the foreground if the user returns to it. If a device never runs out of memory, then Android will keep all of these processes around, truly leaving all applications "running" all of the time."

I can't find any proper callback to use when the Application class is killed excepted onLowMemory(). Does it mean that I have to use this method to persist my data?

Regarding onLowMemory() whose description is quite straightforward, are we talking about a background process or foreground UI?...

If none of application Activities is in foreground and OS is low on memory, it may kill the app so that none of the Application's or the app component's (Activity, Service) callbacks will be invoked. That said, (since you're dealing with Activities) I recommend to store all persistent data as per the documentation, in onPause().

If the Application class is killed on low memory pressure and the app comes to foreground again, how can I know in its onCreate() that the app has been recreated after a system kill?

You can't recognize it in Application's onCreate().

As far as I know, you can't handle the application killed event. Here is a quote from the Application's onTerminate method:

This method is for use in emulated process environments. It will never be called on a production Android device, where processes are removed by simply killing them; no user code (including this callback) is executed when doing so.

The general idea is that you shouldn't care whether the application was killed or not. If it was, the OS will restart the app next time it is needed otherwise it will be resume (and you'll use the Activity / Fragment lifecycle events to achieve this).

What data do you need to store - is it possible to store it earlier (when it is received from web service and so on) instead of waiting for the last moment?

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