[英]My activity invokes onCreate() before onResume()
I am new to Android, but after studying the Activity Lifecycle, I understood that if I minimise the app, it should call onPause()
, and while I reopen it should call onResume()
.我是 Android 的新手,但是在研究了 Activity Lifecycle 之后,我了解到如果我最小化应用程序,它应该调用onPause()
,而当我重新打开它时应该调用onResume()
。 But, in my case, it calls onCreate()
first and then onResume()
.但是,就我而言,它首先调用onCreate()
,然后调用onResume()
。 This is causing my widgets and other variables to enter wrong state.这导致我的小部件和其他变量输入错误的 state。
My app only has an activity.我的应用程序只有一个活动。 Why is the onCreate()
method being invoked before onResume()
?为什么在onResume()
之前调用onCreate()
方法?
It is possible that the app process is killed by the system either from onPause() or onStop() to create room in memory for other apps in the foreground, in which case when you reopen the activity, it will be created.应用程序进程可能会被系统从 onPause() 或 onStop() 杀死,以便在 memory 中为前台的其他应用程序创建空间,在这种情况下,当您重新打开活动时,它将被创建。 In that case onCreate() -> onStart() -> onResume() is the expected sequence.在这种情况下, onCreate() -> onStart() -> onResume() 是预期的顺序。 When the activity is no longer visible, onStop() will be called, so when you navigate back to the activity onStart() -> onResume() is what takes place.当活动不再可见时,将调用 onStop(),因此当您导航回活动时,会发生 onStart() -> onResume()。
More on activity lifecycle here .更多关于活动生命周期的信息。
Additionally, since Android 10 there are some restriction of apps running from background.此外,由于 Android 10 对从后台运行的应用程序有一些限制。 And "an app running a foreground service is considered to be running in the background" which is what you are describing.并且“运行前台服务的应用程序被认为是在后台运行”,这就是您所描述的。 That may be why it is destroyed and app lifecycle starts from onCreate()这可能就是它被销毁并且应用程序生命周期从 onCreate() 开始的原因
If I understand the issue correctly, it sounds like you're receiving a new instance of your Activity when you're looking to resume it instead.如果我正确理解了这个问题,那么当您希望恢复它时,听起来您正在接收一个新的 Activity 实例。 You can change how Activities are handled by setting their launch mode.您可以通过设置启动模式来更改活动的处理方式。
To resume an Activity if it already exists you could change its launchMode
value in your Manifest to something like this:要恢复 Activity(如果它已经存在),您可以将 Manifest 中的launchMode
值更改为如下所示:
<activity
android:name=".MySingleInstanceActivity"
android:launchMode="singleTask" />
There are several launch modes available and there may be one that's better suited for your project.有几种可用的启动模式,可能有一种更适合您的项目。 You can read more about tasks and launch modes at https://developer.android.com/guide/components/activities/tasks-and-back-stack#TaskLaunchModes .您可以在https://developer.android.com/guide/components/activities/tasks-and-back-stack#TaskLaunchModes阅读有关任务和启动模式的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.