I create a new thread in an activity and I rely on onPause() to interrupt the thread. If my app crashes, or the Activity somehow ceases to exist, I want the thread to be kil
If my app crashes
onPause()
is not called here, but this shouldn't bother you as your entire app process ceases to exist, inclusive of all threads you have created (UI or otherwise).
Activity somehow ceases to exist
onPause()
will be called whenever your Activity is moved to the background from the foreground, which is done in every conceivable way in which your Activity can be shut down, except for your app crashing. However, as I mentioned above, the app crashing will also by default kill your thread.
onPause()
is essentially called whenever your Activity is no longer in the foreground. Your Activity may still be alive and in memory after onPause()
has been called, but there is no scenario which I can think of in which your Activity is alive and in the background without onPause()
being called.
Yes , onPause()
will be called when an activity is no longer running. Suppose an activity is closed then the sequence of events will be onPause()
-> onStop()
-> onDestroy()
. Even if your activity slips into the background when another activity starts or when the screen switches off, onPause()
is always called even if the other two methods aren't called. So even if activity ceases, onPause()
will be called and your thread will be killed.
But when your app crashes, along with your entire activity, even the thread that you have started will be taken care of by Android by finishing it all.
Suppose you have two activities A and B. You navigate from A to B. Activity A goes to background ie activity A is paused. Activity B takes focus ie foreground. When you click back button activity B is popped from back stack and activity A takes focus ie activity A resumes.
When you display a dialog in activity the activity in paused and dialog is displayed on click of back button dialog is dismissed and activity resumes (foreground).
When activity is no longer running it is in background so it is paused. I agree with Raghav Sood to what happens when app crashes.
You should usually use the onPause() callback to:
Stop animations or other ongoing actions that could consume CPU. Commit unsaved changes, but only if users expect such changes to be permanently saved when they leave (such as a draft email). Release system resources, such as broadcast receivers, handles to sensors (like GPS), or any resources that may affect battery life while your activity is paused and the user does not need them.
Note :
Multiple tasks can be held in the background at once. However, if the user is running many background tasks at the same time, the system might begin destroying background activities in order to recover memory, causing the activity states to be lost.