Given that only onResume() is guaranteed to run and state is lost after onPause().
Should all initialization be in onResume() instead of onCreate()?
For example,
myDbHelper = new MyDbHelper(getApplicationContext());
It was in onCreate(). Should I move it to onResume()?
I have a listAdapter. Should it be created in onResume()?
For singletons, yes, they would be implemented differently see but what about other variables?
android docs
Now I'm working on something related to your topic. I strongly recommand you to reuse all your variables into onResume(). Becouse you can just finish() your Activity B and for that the only methode that is call in Activity A is onResume(). Also use null pattern object to avoid null pointer exception for your variables.
Not always - onResume() gets triggered when the activity temporarily lost focus (like some pop up event) when the onPause() event was triggered and then you again gain focus (thereby triggering an onResume()). In this case, if you had initialized variables in onResume() they would all be re-initialized at this point and you would lose prior values.
The best example where I can think of where you do stuff in onResume() is when you set up a BroadcastReceiver - you don't want the receiver to trigger something when an alert has come to the foreground (you get the general idea).
Related
Is this safe to assume that when onResume is called all of the member variables native or objects in the activity are still valid ?
In otherwords is it possible that android cleans up any member of an activity under memory stress conditions and then ends up calling onResume ?
When onResume is called anything that was previously set in onCreate, onStart, etc will be there. However if the Activity is deleted due to memory pressure you may have to recreate old values in either onRestoreInstanceState or onCreate, either of which will be called again before onResume is.
I dont think the activity lifecycle guarantees the state will remain on calling onResume. The documentation states that you should reinitialise all components in onPause
https://developer.android.com/training/basics/activity-lifecycle/pausing.html#Resume
An excerpt from the above link:
When the user resumes your activity from the Paused state, the system calls the onResume() method.
Be aware that the system calls this method every time your activity comes into the foreground, including when it's created for the first time
As such, you should implement onResume() to initialize components that you release during onPause() and perform any other initializations that must occur each time the activity enters the Resumed state (such as begin animations and initialize components only used while the activity has user focus).
My app does a lot of setting up in onCreate and then in onResume.
Is it possible that if a device rotation occurs while onCreate is being performed then onResume won't be called?
I'm asking because I receive many crash logs happening in onPause(). The crashes occur, because in onResume() I ALWAYS register some listeners and in onPause they are ALWAYS unregistered. Exception is thrown when a listener that hasn't been registered is unregistered.
So: is it possible that onResume() is not called at all before onPause()?
is it possible that onResume() is not called at all before onPause()?
No. Never.
onResume() Called just before the activity starts interacting with the user. At this point the activity is at the top of the activity stack, with user input going to it.
Always followed by onPause(). So if onPause() of an Activity is being called means onResume() must called.
Read A summary of the activity lifecycle's callback methods for more details.
Is it possible that if a device rotation occurs while onCreate is being performed then onResume won't be called?
Yes possibly, although it seems highly unlikely. Even if you are doing a lot of stuff in onCreate in relative terms you should never be doing so much that it takes several seconds. In other words, for a user to start your Activity and then rotate the device is going to take some finite 'human reaction' time.
If you believe this is happening then...
Reduce the amount of stuff going on in onCreate
NEVER assume that your listeners are registered - check first. Example, when you register a listener set a boolean and only unregister if it's true and set the boolean to false...
Psuedo code:
// To register
if (!isListenerRegistered) {
register(...);
isListenerRegistered = true;
}
// To unregister
if (isListenerRegistered) {
unregister(...);
isListenerRegistered = false;
}
No, http://developer.android.com/training/basics/activity-lifecycle/pausing.html
the sequence is always onCreate(), onStart(), onResume(), then the user sees the activity in the foreground(totally visible). Once another activity starts, this one goes to onPause(), then onStop().
When the device is rotated the activity gets reloaded, so it goes through the destruction steps depending on when the rotation occured. After onDestroy() is called, the creation starts again with onCreate(). Add log messages in your callbacks to see this:
Log.d("DEBUG", "In Activity A's onCreate()");
You can filter your logcat via the log tag, in this case "DEBUG" and see the lifecycle for yourself. Or just step through with the debugger.
This is a text I have copied and pasted from this training tutorial.
"Because the system retains your Activity instance in system memory when it is stopped, it's possible that you don't need to implement the onStop() and onRestart() (or even onStart() methods at all. For most activities that are relatively simple, the activity will stop and restart just fine and you might only need to use onPause() to pause ongoing actions and disconnect from system resources."
I don't understand it. Because to the best of my knowledge, an activity is only stopped by calling onStop() and is only started by calling onStart(). How can an activity start at all without an onStart method.
Do you people understand what they mean in this paragraph?
I think they are confusing you with the word "stop" which appears to have multiple meanings in the paragraph.
I would rephrase it as
Because the system retains your Activity instance in system memory
when it is not in the foreground, it's possible that you don't need
to implement the onStop() and onRestart() (or even onStart() methods
at all. For most activities that are relatively simple, the activity
will suspend and restart just fine and you might only need to use
onPause() to pause ongoing actions and disconnect from system
resources.
The point being is that the App can appear to be stopped, when in actual fact, the system has simply paused it and hidden it from the screen. When the user launches it again, the App doesn't need to start (because it technically hasn't stopped), so it is simply resumed.
When you make an Activity and extend the base class Activity, there is already code in the onStop(), onStart(), and onRestart() methods in the base class.
Your activity simply extends these methods, meaning that you could add more code to them by Overriding them.
So, even though Activities are only started and stopped through those methods, you do not have to explicitly override them in your application. In most cases you won't even have to worry about them: They will be called by the base class from which you are extending.
Please make sure, An Activity starts from onCreate method , then onStart is called by system. If you override onStart method then your overridden method will be also called after onCreate method. If you don't override , then default version of onStart is called.
onStop is called after onPause.
Please check this link , and take a look at Activity life cycle . Your concept will be clear.
Difference between onCreate() and onStart()?
you can use an Activity just fine without - if you need to do something special in onPause() you can override the method:
#Override
public void onPause(){
super.onPause();
// Your magic here!
}
Same goes for onStart(), onStop() etc. You don't need to override the methods but you can if you need to do something specific.
I have manager classes that take an activity as a listener. I use the managers to do threaded calls, work etc and then call back to the listener(activity) when things are done, need changed and so on.
I want to register and unregister the activity as a listener when it is no longer visible. This will prevent unwanted changes from happening (like dialogs appearing when the activity is no longer visible).
My question is, what lifecycle events are best to do this registering. I started with onPause() and onResume() which worked well except when I had an activity that was doing stuff in onActivityResult(). Since onActivityResult() gets called before onResume() my managers are not always registered in time.
Do I need to register in onResume() AND onActivityResult() or is there a better way to approach this?
An alternative approach may be to postpone the processing currently done in onActivityResult() until after the listeners are registered in onResume().
Possible ways of doing this include posting to the message queue, e.g. using a Handler, setting a Runnable object to be called by onResume, or simply storing the result data received by onActivityResult().
This would also ensure that the activity really has come to the foreground when the listener methods are called.
onResume() and onPause() are the best for this. The onDestroy(), per the documentation, is not guaranteed to be invoked though this is a favorite for many people, so stick with the pauses and resumes.
You can have the handle of the current Activity in the Manager class. Register its presence on onCreate() and unregister it on either onCreate() by some other Activity, or onBackPressed() of the current Activity.
On a related note, I would recommend an MVC (or similar) architecture where the controller has awareness of the view's status (the controller can track the onCreate() and onBackPressed() of each Activity).
According to the android Activity Lifecycle, the only callback guaranteed to be called (if an activity ever leaves the Running state, which is typically expected) is onPause().
So, I must assume that there are scenarios in which it makes sense to implement onStop() and onDestroy() although they are not really guaranteed to be called.
I understand that onStop() should be implemented when it's possible for an activity to return to the Running state via the Stopped state (why would it do that instead of returning directly is a different question).
But the need for onDestroy(), when I can place all cleanup/state-saving into onPause(), is unclear to me.
Can you describe a real-app situation (i.e. not analogy to driving a car etc.) in which it would make sense to implement onDestroy()?
onDestroy will be called if you explicitly call finish(); yourself.
Your main activity calls startActivityForResult on a map activity.
Map activity with a LocationListener, the user clicks the map and selects say a local restaurant.
The activity then , sets up some extras to be sent back to your main activity, it then explicitly call's finish(); on itself and in the onDestroy kills the LocationListener and other variables you had invoked.
Just found this in the docs
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.
Can you describe a real-app situation
(i.e. not analogy to driving a car
etc.) in which it would make sense to
implement onDestroy()?
When you want to capture a configuration change. It's all in the SDK:
http://developer.android.com/reference/android/app/Activity.html