Check whether activity is active

前端 未结 8 2288
眼角桃花
眼角桃花 2020-11-27 04:47

I\'m having a problem with a listener in a certain activity.

The problem is that this listener contains an alert.show(); which can be called after we try to push a

8条回答
  •  不知归路
    2020-11-27 05:12

    For API level >= 23 you can use 'lifecycle' property of activity to detect the state of activity. This gives a very compact code. Here is an example code in Kotlin, as class extension:

    fun FragmentActivity.isRunning() = lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)
    
    // ...
    // Here 'myActivity' can be inherited from different activity-like classes, 
    // for example, from class AppCompatActivity:
    if (myActivity.isRunning()) {
        Log.d("log", "Activity is running!")
    }
    

提交回复
热议问题