Question

In my app, when user presses HOME key and returns back to app after some time, my app gives NullPointerExceptions on various places and activities. I know that my app is being killed by OS to free some resources. Now I want that when user comes back again to app and app was previously killed, then how can I detect that my app was killed so that I can reload different resources?

Was it helpful?

Solution

When onCreate (Bundle savedInstanceState) is called, check that savedInstanceState is not null. As stated by onCreate :

savedInstanceState If the activity is being re-initialized after previously being shut down then this Bundle contains the data it most recently supplied in onSaveInstanceState(Bundle). Note: Otherwise it is null.

See also onSaveInstanceState() which is not part of the normal lifecycle but is called before the activity is killed.

Note : if the user does A ----> B ----> C --back--> B ----> C, the second time C is created the passed bundle will be null, as it is a new instance, not the same recreated after being killed.

OTHER TIPS

Basically: look at the picture on this page: http://developer.android.com/reference/android/app/Activity.html

enter image description here

the various functions that are called in different situations are onCreate, onStart and onResume.

My suggestion would be: implement your own Application and if the onCreate() is called, the app was killed in background

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top