3

我首先尝试使用 onStart() 或 onResume()。但是,使用它们有两个缺点。

1,如果我开始另一个活动并稍后将其关闭,如下所示。(有点像模态显示一个新的视图控制器,然后将其关闭)

private void dismiss() {
   Intent intent = new Intent();
   intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
   intent.setClass(this, MainActivity.class);
   startActivity(intent);
   finish();
}

onResume() 仍然会被调用

2,我不能在其他活动中重复使用相同的登录。

因此,不知Android中是否有一个方法与Android中的-(void)applicationWillResignActive:(UIApplication *)application一模一样

4

3 回答 3

3

您可以使用 onRestart() 方法。仅当您的应用从后台进入前台时才会调用此方法。

这两种方法的相似之处:

它类似于“某些案例”中的 appDidBecomeActive。每当您进入后台,即从 Activity 到主屏幕时,都会调用 onPause(),然后调用 onStop() 方法。然后你恢复到 android 中的应用程序,然后调用 onRestart() 和 onPause() 方法。

进入主屏幕时 iOs 中的生命周期:(App 委托生命周期方法)appWillEnterForeground -> appDidBecomeActive

从主屏幕进入前台时 Android 中的生命周期:(活动生命周期方法)onRestart()->onResume。

从上面可以看出onRestart类似于appWillEnterForeground,onResume类似于appDidBecomeActive;但我们可以使用 onRestart 而不是 onResume 作为 appDidBecomeActive 因为:

  1. 每次应用程序从一个活动移动到另一个活动时,都会调用 onResume。所以我们最好避免使用 Activity (ViewController) 特定的方法。此外,onResume 类似于 iOS 中的 viewWillAppear 方法。
  2. onRestart 方法仅在应用程序从后台进入前台时调用,如 appDidBecomeActive 方法,因此更像是应用程序委托方法。

这两种方法的区别:

onRestart() 方法不会在第一次(在应用启动时)被调用,因为 appDidBecomeAcitve 被调用。

应用程序启动期间 iOS 中的生命周期:(应用程序委托生命周期方法) AppDidFinishLaunchingWithOptions -> appDidBecomeActive

应用启动期间Android中的生命周期:(活动生命周期方法)
onCreate()->onStart()-> onResume()

于 2015-05-07T19:08:02.853 回答
0

如果您使用您的代码将MainActivity其放在前面,您可以像这样检测到这一点:dismiss()MainActivity.onNewIntent()

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    if ((intent & Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
        // I've been brought to the FRONT by another activity
    }
}

这有帮助吗?我不是 100% 确定我明白你想要什么。

于 2013-04-29T16:26:41.903 回答
0

由于 Android 中的应用程序可能由多个活动组成,因此相当于 applicationDidBecomeActive 是当没有活动处于运行状态时,其中一个活动又回来了。applicationDidEnterBackground 等价于应用程序的所有活动停止时。

有一种简单的方法可以使用 ProcessLifecycleOwner 进行跟踪:https ://developer.android.com/reference/androidx/lifecycle/ProcessLifecycleOwner

        ProcessLifecycleOwner.get().lifecycle.addObserver(object : LifecycleEventObserver {
        override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
            when (event) {
                Lifecycle.Event.ON_RESUME -> {
                    Log.i("ProcessLifecycleOwner", "app to foreground")
                }
                Lifecycle.Event.ON_PAUSE -> {
                    Log.i("ProcessLifecycleOwner", "app to background")
                }
            }
        }
    })
于 2021-10-27T18:45:08.947 回答