重写的 android 生命周期方法如何可以 运行 超级调用后的代码而不去其后续的生命周期方法

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

看看这个。

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

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

假设此代码来自 activity,它是 Activity class 的子代。 super.onCreate()onCreate() 中的第一条语句。这个超级调用必须连接点通知父class派生class中调用了onCreate(),可以调用下一个生命周期方法,显然是onStart()

也就是执行顺序必须是这样的:

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

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

但它看起来像这样工作:

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

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

怎么可能?

因为onStart()onCreate()之后被调用的,而不是来自它。

看看here.

ActivityThread#startActivityNow() 实例化 Activity 并调用 onCreate().

再往下几行,您会看到对 ActivityThread#handleStartActivity() 的调用,也就是对 onStart().

的调用

由于那里没有异步,Java 将等待 onCreate() 完成后再继续并最终调用 onStart().

查看 source comments in Activity.java 了解有关 Activity 生命周期如何工作的更多详细信息。