In my Activity, I have overrode onDestory() and just put a log call to show if this method is being called. (tested on Android 4.2.2 and 4.4.4)
#Override
protected void onDestroy() {
Log.i(TAG, "onDestroy() was called");
super.onDestroy();
}
When I press the back button, this method gets called (I saw the log).
I believe this should not happen unless phone gets low in memory or something. I have nothing much in the app but the MainActivity and some fragments.
Here is the log when the user is in the MainActivity and presses the back button:
I/MainActivity? onBackPressed() was called
I/MainActivity? onStop() was called
I/MainActivity? onDestroy() was called
Why this happens?
I also checked for isFinishing() in the onPause() and it always returns true
From the Javadoc :
Perform any final cleanup before an activity is destroyed. This can
happen either because the activity is finishing (someone called finish
on it, or because the system is temporarily destroying this instance
of the activity to save space. You can distinguish between these two
scenarios with the isFinishing method. Note: do not count on this
method being called as a place for saving data!
When you press back button inside an Activity, it will call finish(), which will "close" it.
Activity.java
/**
* Called when the activity has detected the user's press of the back
* key. The default implementation simply finishes the current activity,
* but you can override this to do whatever you want.
*/
public void onBackPressed() {
if (!mFragments.popBackStackImmediate()) {
finish();
}
}
When it happens, onDestroy() can (and usually will) be called.
protected void onDestroy ()
Perform any final cleanup before an activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.
The same reason also goes to why putting isFinishing() inside onPause() always returns true, if you press the back button (call finish()). It will not return true if you hide the Activity with other method, e.g. pressing the home button.
Related
Is there any way to prevent executing code within onResume when returning to an application after the home button has been pressed?
What method is called when the home button is pressed? I could possibly flag something up when home button is pressed?
Thanks
After overriding above method, now you can easily listen HOME Key press in your activity using onKeyDown() method.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_HOME)
{
//The Code Want to Perform.
}
});
Hope this will help
Thanks for the help everyone I managed to solve this by creating a boolean, executeOnResume, which I make false everytime onStop() is called and the app is closed. I then check the state of this boolean in onResume() when the app is opened again to choose whether some code should be executed or not.
onStop()
//-----application stopped
#Override
protected void onStop() {
super.onStop();
//do not execute onResume code when app opened again
executeOnResume = false;
}
onResume()
//-----application resumed
#Override
protected void onResume() {
super.onResume();
//if true
if (executeOnResume) {
//do something
}
else {
//execute onResume true code the next time onResume is called. For example, returning from another activity
}
}
tapping the Home button creates an intent to launch the Home screen and then starts that inten
Correct.
If this is the case, I'd expect the onCreate() method to be run whenever the Home screen is created
Not necessarily. If it is already running, it would be called with onNewIntent().
If someone could just offer some enlightenment into this matter, the basic question is whether onResume() or onCreate() gets called when I tap the Home button
Any time any activity returns to the foreground from a user input standpoint, onResume() is called. Home screens should be no different in this regard.
onCreate() is called when the activity is created. Existing activities are not created, but are merely brought back to the foreground. If what triggered the activity to return to the foreground was a startActivity() call, the activity will be called with onNewIntent() and onResume() (and usually onStart(), for that matter).
Reference : Which method is run when Home button pressed?
Users can leave your app in all kinds of different ways. Pressing HOME is only one of them. An incoming phone call will leave your app, pulling down the list of notifications and pressing one will leave your app, etc. In all of these cases, when the user returns to your app, onResume() will be called. This is standard Android behaviour and tells your app that it is now in the foreground and visible to the user.
Your architecture is flawed if you need to know how the user is returning to your app. You probably need to move some code that you have in onResume() back to onCreate() or onNewIntent().
There is a function in my android app that needs to run every time the user tries to edit his or her profile. There are two parts of edit profile in my app (please don't ask why, it has a very long tedious reason behind it). I need to revert back the changes the user did in the first part of the edit profile if the user decides to cancel everything. I have made a cancel button in the part two of edit profile but my question is, what if user presses the return button or the home button on the device and the app calls the onPause() and on onStop()? how can I run the same code in these two phases of the activities? Anyone out there who knows how to put code in different states on activities? Do I just make a function onPause() and stick the code in there? Would that work?
Yes, it should definitely work. In your case, you should write your code in onPause() method.
Here is a summary of the Activity Lifecycle:
onCreate():
Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one.
Always followed by onStart().
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Write your code here
}
onStart():
Called when the activity is becoming visible to the user.
Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.
#Override
public void onStart() {
super.onStart();
//Write your code here
}
onResume():
Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it.
Always followed by onPause().
#Override
public void onResume() {
super.onResume();
//Write your code here
}
onPause():
Called when the system is about to start resuming a previous activity. This is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, etc. Implementations of this method must be very quick because the next activity will not be resumed until this method returns.
Followed by either onResume() if the activity returns back to the front, or onStop() if it becomes invisible to the user.
#Override
public void onPause() {
super.onPause();
//Write your code here
}
onStop():
Called when the activity is no longer visible to the user, because another activity has been resumed and is covering this one. This may happen either because a new activity is being started, an existing one is being brought in front of this one, or this one is being destroyed.
Followed by either onRestart() if this activity is coming back to interact with the user, or onDestroy() if this activity is going away.
#Override
public void onStop() {
super.onStop();
//Write your code here
}
onDestroy():
The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.
#Override
public void onDestroy() {
super.onDestroy();
//Write your code here
}
You can do many things inside both onPause and onStop, just remember to call super.onPause();, super.onStop(); or whatever you need inside each one, just follow the pattern below. Simply add the code to your Activity and you're good to go.
#Override
public void onPause() {
super.onPause(); // Always call the superclass method first
// Do what you want.
}
Additionaly, if you want your users to be able to go back on your activity and edit something instead of closing it, you can just call onBackPressed():
#Override
public void onBackPressed() {
super.onBackPressed();
// You can just call onStop to close the app
// or do what you want.
}
Only onPause is guaranteed to be called
I am new to android.I have learned that the onPause() method is called when some other activity comes in the foreground and onStop() method is called when an activity is no longer visible.Can someone please explain what's the difference between going in background and becoming invisible giving some practical example.
Best example? A popup, your activity is still visible, so only onPause() is called. Becoming invisible is when another activity is launched, the app is sent to the background, the user switches to another app et.
Think about two cases
1. Calling Activity B as dialog
In this case, some part of Activty A will be visible. So only onPause() method will get called for Activity A. And when you will be back from Activity B to A, onResume() of Activity A will get called.
2.Calling Activity B as normal activity
In this case, Activity A will be completely invisible, So onPause() and onStop() both will be called. And when you will be back from Activity B to A, onRestart(), onStart() and onResume() methods of Activity A will be called.
Have a look
Case 1: If you call normal activity. (Which is going to hide caller activity)
onPause()
onStop()
<------- Back to caller
onRestart()
onStart()
onResume()
Case 2: If you call activity-as-dialog. (Which is going to partially hide caller activity)
onPause()
<------- Back to caller
onResume()
whenever a dialog box appears on any activity then activity's onPause() called and this activity holds the first position in stack(Top), on the other hand whenever we switches activity from one to another the previous activity's on Stop() method called and its automatically garbage collected in sometimes.
onCreate() does not get called when I leave the application using back button and start it immediately. I believe this is because, Android has not killed the application process yet. I tried using #AfterViews, the same happens. How could I make sure that every time the application is started, my specific code runs?
Does not get called when I leave the application using back button and then start.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
methodToRun();
}
I use this onBackPressed() to exit the application.
#Override
public void onBackPressed() {
this.moveTaskToBack(true);
this.finish();
}
Even #AfterViews does not get called when I leave the application using back button and then start.
#AfterViews
void checkAgreementFlag(){
methodToRun();
}
I want methodToRun() to always get called. How would I do it?
Call methodToRun() from onResume() of activity.
onResume(): Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it.
onCreate(): is called when your application is starting first time.
onRestart(): Called after your activity has been stopped, prior to it being started again.
onStart(): Called when the activity is becoming visible to the user.
onStop() : When the activity is no longer visible.
For the back key scenario activity lifecycle:
onCreate()->onStart()->onResume()->Activity running
After pressing back key
onPause()->onStop()
If the activity is coming back then
onRestart()->onStart()->onResume()->Activity running
otherwise onDestroy() will be called.
I was testing out this code which shows which state an activity is in
public class Activity101Activity extends Activity {
String tag = "Lifecycle";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
setContentView(R.layout.activity_activity101);
Log.d(tag , "In the onCreate() event");
}
public void onStart()
{
super.onStart();
Log.d(tag , "In the onStart() event");
}
public void onRestart()
{
super.onRestart();
Log.d(tag , "In the onRestart() event");
}
public void onResume()
{
super.onResume();
Log.d(tag , "In the onResume() event");
}
public void onPause()
{
super.onPause();
Log.d(tag , "In the onPause() event");
}
public void onStop()
{
super.onStop();
Log.d(tag , "In the onStop() event" );
}
public void onDestroy()
{
super.onDestroy();
Log.d(tag , "In the onDestroy() event");
}
}
so I see that onDestroy() is only called when we press the back button while the activity is on screen, and is never called otherwise. So it should be running in the back ground if I press the home button while the activity is running. However, if I go to Settings -> Apps -> Running I can't see it on the list. So does that mean it is running in the background or not?
Again, Again, this code shows that onPause() is always followed by onStop() and onStart() is always followed by onResume(). So why are they defined as different functions in the Android environment and not combined?
Here I give you biref idea of activity life cycle...
onCreate():
Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one. Always followed by onStart().
onRestart():
Called after your activity has been stopped, prior to it being started again. Always followed by onStart()
onStart():
Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.
onResume():
Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it. Always followed by onPause().
onPause ():
Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume(). When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A's onPause() returns, so be sure to not do anything lengthy here.
onStop():
Called when you are no longer visible to the user. You will next receive either onRestart(), onDestroy(), or nothing, depending on later user activity.
Note that this method may never be called, in low memory situations where the system does not have enough memory to keep your activity's process running after its onPause() method is called.
onDestroy():
The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.
So..onStart method call when activity comes in the foreground without interaction of user...and onResume method call when user starts interaction...so the functions of all methods is different ..
And once you press home button or back button your app running in the background and once you kill it from task manager it will shows nothing in the settings...
Once the activity goes in backstack, it is in suspended mode. So you dont see it in running app list. Once you relaunch such suspended application, it comes to foreground from backstack and starts to run. It is kept in backstack to preserve its state and resume from the place where it got stopped before going in background.
To understand why, onStart is needed before onResume follow the link below. It will clear all your doubts very clearly:
Difference between onStart() and onResume()
onStart isn't always followed by onResume. onStart is called when you Activity is visible, and onResume is called when your Activity is active. For example, an Activity could be visible but not active if there was a dialog partially covering it.
Thats' because there's a chance that onStart might not get called even when onResume actually is, there's a scenario when the activity might go to onPause only, without going to onStop [it only happens when activity is partially visible, not completelly covered by another activity], hence when comming back to activity only onResume will be called and not onStart.
Same with onPause, its always executed before onStop but onStop might not be called after onPause, as mentioned before, it could be called without onStop being actually called. If you press HOME you will not see the behavior i just explained because the activity is not partially visible, in order to reproduce it you have to find a way to make another component come on top without completely covering the activity...
Hope this helps.
Regards!