有没有更好的方法来了解 Activity 的生命周期状态,例如 isOnStop、isOnPause 等 API?

lxa*_*der 0 java android

我有很多变量,例如isOnPauseisOnStop等等。当 Activity 调用时,onStop()isOnStop = true想知道是否存在像这样的官方方法this.isOnPause(), this.isOnStop()

我查了Activity的API参考,只看到了isDestroyed(),但是没有isStoped(), isPaused()

protect final void onStop(){
    isOnStop = true // I don't think this is good way to do this.
}
Run Code Online (Sandbox Code Playgroud)

所以,我想知道是否存在像这样的官方方法this.isOnPause(), this.isOnStop()

ian*_*ake 5

扩展FragmentActivity或时AppCompatActivity,您可以使用 访问当前生命周期状态getLifecycle().getCurrentState()这将返回Lifecycle.State 枚举值之一,该值具有isAtLeast()方法,允许您编写如下代码

Lifecycle.State state = getLifecycle().getCurrentState();
// The state could be either STARTED or RESUMED
boolean isStarted = state.isAtLeast(Lifecycle.State.STARTED)

// Paused means we aren't resumed
boolean isPaused = !state.isAtLeast(Lifecycle.State.RESUMED)
Run Code Online (Sandbox Code Playgroud)