Activity life cycle confusion - android

The life cycle of an activity is documented in many places but I couldn't find the thing I need. This is my activity, it have a constructor and the onCreate method. In my project I have also a logging in this methods and every time when I go from portrait to landscape I see that both methods are executed. Why my the constructor is called ? isn't the activity in the stack and the instance of my activity is in the memory so when the configuration change is happen, then only the oncreate and on retainistancestate should happen (of course the onResume). Why the constructor is called every time, who is calling ? Is it every time when something get changed from the configuration both methods are guaranteed to be called (one after another, in this same sequence).
public TestActivity()
{
super(R.menu.main_menu, tag);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
I was playing with my sample app but I want to know more details, can someone clarify me the scenario when the constructor is included ?, I founded a a lot of documentation about life-cycle but none explains the details when the constructor is included
Edit1:
I read in some places that there is stack in witch the activities are putted in so the next time they go up and running faster, but what when the configuration get changed ? Is it must to to call the constructor and the oncreate methods ?

On rotation your activity will be restarted complete. You can prevent that with android:configChanges="keyboardHidden| orientation" in your manifest.

As #rekire answered, the activity is restarted on screen rotation. Here restart means that the framework creates another instance of the activity, that's why the constructor of your activity class is called and then the onCreate(). The new activity instance replaces the old one which will be finally recycled by GC, if its reference isn't held by others.
If you want to avoid activity restart on screen rotation, please read this question.
I've drawn an UML diagram to describe the Android activity life cycle.

Hence there are no reason having constructor to invoke activity unless you have constructor with params(onCreate invoke it for us anyway...). However basically it seems like a java thing onCreate probably calling activties's default constructor which is
public ActivityName(){} // This might get call because onCreate somewhere under the hood invoking Activity :)
Try same thing with constructor with param like
public ActivityName(String s){}// This wouldn't be call unless you explicitly call it.
Hope this will help,
I would wait for more expert answer though :)
Edit : So when you rotate your phone which calls onCreate as it will get created again and onCreate probably calls default constructor to invoke instance of your activity :)... I forgot to mention this earlier.

Related

Understanding activity lifecycle

I am just starting my experience with Android development (I am watching tutorials right now). I looked at the activity lifecycle on the Android developers page, and I realized that the activity always goes through the onResume() method before it's visible to the user. Assuming I will be using no fragments in the activity, does that mean that most of the code logic should be within the onResume() method, and I should just inflate the layout once inside the onCreate() at the beginning?
Please Refer the site for the better understanding of the activity lifecycle
https://developer.android.com/guide/components/activities/activity-lifecycle
and also this for brief understanding
https://www.javatpoint.com/android-life-cycle-of-activity
Now answering your question onCreate() is not just for inflating the layout.
The main part of the core logic is written here and onResume() is called when you minimize the or open the app once again it is called again and again but onCreate() is called once untill and unless the control is not forwarded to another activity
Like in Java the start running from
public static void main(String[] args){
}
In Android(Activity) the first line will be executed will be from onCreate() and not from the onResume()
if you will practice the same and will habitual of this process again and again then you better understand what i m trying to tell nothing can be more useful than you practice and your understanding try to print the toast or Log on each and every state of the activity lifecycle and you better understand this without the help of anyone
Cheers Happy Coding!

Initialize views of activity in android

Is it necessary to initialize all the views of activity in onCreate() only. Can you tell me best initializations of views of activity.
Thanks
No need to initialize any view if you do not modify it.
you can initialize in any Activity lifecycle as your wish(before accessing).
But is is said as best practice to initialize it in onCreate().
Why:
if you see the lifecycle OnCreate is called when you app page is not shown. Like onStart called when app is partially visible & onResume is called when it is fully visible. So, mostly we want everything ready before seeing it. So that is one reason.
Another is findViewById is bit more expensive. So, we don't want to see that when app is visible.
OnStart & onResume may call multiple time when you go another page. So, it's preferable to initialize everything only once , than multiple time.
So, choice is yours now.
OnCreate() : This method is called once when activity is to be created. That is why all the gobal and static content should go there. Example - This may include your shared preferences, databases initialisations.
OnStart() : This method is called when you see your activity over screen. It is foreground method. OnStart() ends with OnStop(). Example : Let us assume A and B activity, A activity has been created and currently in onStart() method is being called. When one switches to B activity then A's OnStop() method will be called and B activity will be created. Thus OnStart() and OnStop() methods are called when you switches onto activities.
So according to your question initialisation is done once so it should be done in OnCreate() method if it is done in OnStart() then initialisation will takes place every time when you switch between activities.
Source : Difference between onCreate() and onStart()?
Please take a look over here this will clear your all faults regarding life cycle Activity | Android Developer

Android - Application onCreate method - does it ALWAYS get called first?

I am preparing new version of one of my apps, and I made such huge changes in my app, that I need to do some data conversion exactly after update of app as absolutely first thing (before doing anything else). I figured out, that best place to do it would be in my class (which extends Application) in onCreate() method. I tested it few times, and it seems to work ok, but then I read documentation:
Base class for those who need to maintain global application state.
You can provide your own implementation by specifying its name in
your AndroidManifest.xml's tag, [b]which will cause
that class to be instantiated for you when the process for your
application/package is created[/b].
It looks like I am right, but I am not quite sure. Can you confirm/disprove it?
The Application constructor will be called first. Then the Application::onCreate() method will be called. The only exception I know of is if the Application contains a ContentProvider, it can receive calls before the Application does.
This is from here: http://developer.android.com/reference/android/app/Application.html#onCreate()
public void onCreate ()
Added in API level 1 Called when the application is starting, before
any activity, service, or receiver objects (excluding content
providers) have been created. Implementations should be as quick as
possible (for example using lazy initialization of state) since the
time spent in this function directly impacts the performance of
starting the first activity, service, or receiver in a process. If you
override this method, be sure to call super.onCreate().
Yes, that is right. You should do all your initial app configuration in the onCreate() method of the Application.
Besides if you use sqllite you can make migration in onUpgrade method of the SQLiteOpenHelper.
http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html
I have not tested it, and maybe there are some more relevant options out there, but for the upgrade the following looks promising: SQLiteOpenHelper.onUpgrade( SQLiteDatabase db, int oldVersion, int newVersion ).
So you can hang your update routines on that. The method you override should fire only when the database upgrade is needed.
Yes. The application onCreate method is the first method that is called when the process is started. you can put your code there without any problems.
here the documentation http://developer.android.com/reference/android/app/Application.html#onCreate()
Called when the application is starting, before any activity, service, or receiver objects (excluding content providers) have been created. Implementations should be as quick as possible since the time spent in this function directly impacts the performance of starting the first activity...
be careful to make all the changes very quickly and be sure that you call the "upgrade" method only once.
Consider also the possibility to put this method in an AsyncTask, if its possible.
No it dosent..say you have activity A(launcher activity) and B...when you launch your app ...A loads starting from onCreate()...and say u started activity B, then it launches B and its onCreate method is executed..but now if you navigate back to A..it will call th onResume activity and not the onCreate..

Getting around onDestroy being called on orientation change?

I have a stock Nexus 5 running 4.4.2 (using ART if it matters) and I've found an interesting scenario. I have this as my onDestroy():
#Override
protected void onDestroy() {
super.onDestroy();
t.setText("onDestroy");
t.show();
}
It's a GPS oriented app so I'm up and walking around. I am using the technique mentioned in this question to show a lot of debug toast messages.
Anyway, when I rotate my app, the toast appears. I understand that the activity is destroyed and recreated for the new orientation, but how can I know what's really going on? How can I tell when my app is REALLY getting destroyed and not just being rotated? Similar to this question, I want to log out when a particular activity is destroyed.
Since Honeycomb, the isChangingConfigurations() method can be queried to check whether the Activity is being recreated due to configuration changes. Alternatively, the isFinishing() method can be queried on any API level to check whether the Activity is actually being finished, or is only being destroyed temporarily by the system.
As far as I can determine, the two methods should always return mutually consistent results in practice. The only point where they might have diverged is when the system kills the process to clear memory, but there are no callbacks or interaction with the app at that point.
The documentation of the onDestroy() method mentions the use of the isFinishing() method:
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.
You can put it in a fragment with setRetainInstanceState(true) set. Place your code in the onDestroy() method of the fragment. Then, the fragment will not be destroyed on orientation changes.
First of all, you should not use onDestroy() to do anything because its not guaranteed to be called. I would put things on the onPause() method; I wouldn't even put things in onStop().
Also, Im not sure why you want to log out a user when they navigate away from the app. I would rather implement some kind of timer on the app or server to log out after x time.
Now, the answer lies in the documentation: http://developer.android.com/reference/android/app/Activity.html#ConfigurationChanges
You might want to override onConfigurationChanged so that your activity is not restarted.
I found a couple of solutions which are really just patterns to detect when the screen rotates. Alternatively, you can determine that the device was actually destroyed by checking some static data member to see if it was initialized or not.
Configuration changed solutions:
The first one involves handling all of the configuration changes in the onConfigurationChanged callback.
"Note that this will only be called if you have selected
configurations you would like to handle with the configChanges
attribute in your manifest."
The second involves listening for Display.getRotation() which returns a Surface.ROTATION_* object. Which is the new orientation of your screen relative to the natural state of the device orientation.
Again, you can use the configuration changes along with the static member.
Add ConfigChanges.UiMode flag to the ConfigurationChanges attribute for your MainActivity class, and this solves the problem.
More details: Android Launcher "OnDestroy" gets called twice

Is it okay for me to implement a switch statement in the onCreate method?

I currently have an activity's onCreate() method set to capture an intent the first thing it does. The intent will always have an extra int "ACTIONCODE" that determines what the activity should do.
Activity A might want activity Z to set up variables for the first time, so it calls startActivity(includedIntent) which has some extra int ActivityZ.SET_UP_FIRST_TIME (which is a constant in Activity Z.) Activity B might want to change the variables around a bit, so it does a startActivity(includedIntent) with the intent now including an extra int ActivityZ.CHANGE_VARIABLES as well as other data to change those variables.
Activity Z could just be a bunch of textviews that display what its variables are. Depending on what ACTIONCODE it receives from getIntent(), it will perform things just as it needs to.
I feel like I have a lot more control over the activities in my app my doing this, yet I fear as though it might be a really naive and inefficient implementation. I basically do not trust (nor fully understand) onStart(),onResume(),onPause(),and onStop(). From what I've heard, there is no guarantee that an activity will always return back to onResume(). While it was in its onPause() or onStop() state, it could have been killed or completely destroyed by the system, and thus would only return back to onCreate() again. It's the only method that I trust.
I even do all of my data saving from onCreate(). Why? I heard that if an activity is in onPause() or onStop(), it is liable to be killed, and may not even finish running through all the lines included in the overridden onPause() or onStop() method. I don't want to perform a data saving function from within a method that could abruptly stop!
Is my thinking wrong here? Are my fears irrational? If so, what should I do instead?
Here are my app screenshots by the way:
Thanks, Luksprog. After some reading, I think I can trust the activity lifecycle better now.
I will implement setting up in onCreate, loading in onResume, and saving in onPause! Hopefully that's correct.
Now all I need is some advice on the right way to set up activities and fragments. I just need some general rule of thumb for deciding when and when not to start a new activity, or if it may be better to use fragments.

Categories

Resources