简体   繁体   中英

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() . But, in my case, it calls onCreate() first and then onResume() . This is causing my widgets and other variables to enter wrong state.

My app only has an activity. Why is the onCreate() method being invoked before onResume() ?

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. In that case onCreate() -> onStart() -> onResume() is the expected sequence. 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.

More on activity lifecycle here .

Additionally, since Android 10 there are some restriction of apps running from background. 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()

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. 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
        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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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