简体   繁体   English

如何知道活动已经结束?

[英]How to know activity has been finished?

I want to check to see if an activity is running or finished.我想检查活动是否正在运行或已完成。 Is there any method through which I can check the status of activity?有什么方法可以检查活动的状态吗?

I found activity.isFinishing() but I am not sure about it.我找到了activity.isFinishing()但我不确定。

If you want to perform any step before Activity is going to become invisible. 如果要在Activity变为不可见之前执行任何步骤。

Their are several choices here. 他们有几种选择。

onDestroy() - for final cleanup. onDestroy() - 用于最终清理。

isFinishing() - right after act.finish() is called it will return true. isFinishing() - 在act.finish()之后,它将返回true。

onStop() - when the Activity is killed by framework process. onStop() - 当Activity被框架进程杀死时。 (not destroyed) (未销毁)

onPause() - when the Activity is covered by any other Activity onPause() - 当Activity被任何其他Activity覆盖时

onBackPressed() - capturing the event of hardware Back key triggered by user. onBackPressed() - 捕获用户触发的硬件返回键事件。

Call isFinishing in the onPause method before the activity is destroyed: 在销毁活动之前,在onPause方法中调用isFinishing:

@Override
protected void onPause() {
    super.onPause();
    if (isFinishing()) {
        // Here  you can be sure the Activity will be destroyed eventually
    }
}

I realize this is very old, but for anyone using Kotlin:我意识到这已经很老了,但对于任何使用 Kotlin 的人来说:

We can check within a Fragment:我们可以在 Fragment 内检查:

// FRAGMENT
override fun onPause() {
    super.onPause()
    // Log.v(TAG, "onPause");
    if(requireActivity().isChangingConfigurations) {
         // Config change
    } else {
        if(requireActivity().isFinishing) {
            // deal with activity ending (finish up viewModel etc)
        }
        // deal with rotate or other config changes as required
    }
}

Of course, we can also just do this directly inside an activity (just remove the requireActivity() parts).当然,我们也可以直接在 Activity 中执行此操作(只需删除 requireActivity() 部分)。

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

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