Bertram Gilfoyle
Bertram Gilfoyle

Reputation: 10235

How an overrided android life cycle method can run the code after the super call without going to its succeeding life cycle method

Take a look at this.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
protected void onStart() {
    super.onStart();
}

Assume this code is from a normal activity which is a child of Activity class. super.onCreate() is the first statement in onCreate(). This super call must the connecting point to notify the parent class that the onCreate() is called in derived class and the next lifecycle method can be called, which is onStart() obviously.

That is, the order of execution must be like this :

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);              <-- ( 1 )
    setContentView(R.layout.activity_main);          <-- ( 3 )
}

@Override
protected void onStart() {
    super.onStart();                                 <-- ( 2 )
}

But it looks like working this way instead :

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);              <-- ( 1 )
    setContentView(R.layout.activity_main);          <-- ( 2 )
}

@Override
protected void onStart() {
    super.onStart();                                 <-- ( 3 )
}

How is it possible?

Upvotes: 1

Views: 102

Answers (1)

TheWanderer
TheWanderer

Reputation: 17844

Because onStart() is called after onCreate(), not from it.

Take a look here.

ActivityThread#startActivityNow() instantiates the Activity and calls onCreate().

A few lines down you'll see a call to ActivityThread#handleStartActivity() which is what calls onStart().

Since there's no async there, Java will wait for onCreate() to finish before it continues and eventually calls onStart().

Check the source comments in Activity.java for more details on how Activity lifecycles work.

Upvotes: 3

Related Questions