问题
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?
回答1:
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.
回答2:
Basically: look at the picture on this page: http://developer.android.com/reference/android/app/Activity.html
the various functions that are called in different situations are onCreate
, onStart
and onResume
.
回答3:
My suggestion would be: implement your own Application
and if the onCreate()
is called, the app was killed in background
来源:https://stackoverflow.com/questions/14377668/android-how-to-detect-on-resume-that-my-app-was-killed-by-vm