简体   繁体   English

一个重写的android生命周期方法如何在超级调用之后运行代码,而无需使用其后续的生命周期方法

[英]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. 假设此代码来自正常活动,该活动是Activity类的子代。 super.onCreate() is the first statement in onCreate() . super.onCreate()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. 这个超级调用必须连接点通知父类在派生类中调用onCreate()并且可以调用下一个生命周期方法,显然是onStart()

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? 这怎么可能?

Because onStart() is called after onCreate() , not from it. 因为onStart() onCreate() 之后调用的,而不是来自它。

Take a look here . 看看这里

ActivityThread#startActivityNow() instantiates the Activity and calls onCreate() . ActivityThread#startActivityNow()实例化Activity并调用onCreate()

A few lines down you'll see a call to ActivityThread#handleStartActivity() which is what calls onStart() . 几行后你会看到对ActivityThread#handleStartActivity()调用,调用onStart()

Since there's no async there, Java will wait for onCreate() to finish before it continues and eventually calls onStart() . 由于那里没有异步,Java将等待onCreate()在继续之前完成并最终调用onStart()

Check the source comments in Activity.java for more details on how Activity lifecycles work. 检查Activity.java中源注释,以获取有关Activity生命周期如何工作的更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM