Search code examples
androidandroid-activityandroid-lifecycle

Can onActivityResult() be called before onCreate()?


Can onActivityResult() theoretically be called before onCreate? I know it can be called before onResume(), but let's consider this extreme case:

  1. activity A is running and starts activity B for a result
  2. activity B opens
  3. the device is running low on memory, so it destroys activity A
  4. activity B finishes with a result

What happens now? Does activity A get re-created before receiving the result, or does it receive the result before onCreate()? Is this guaranteed to be in the same order each time?


Solution

  • You will commonly see this if you are opening an app to scan a barcode or take a photo or video. The Activity you launch to do that requires a lot of resources so Android kills the OS process hosting your app.

    When the Activity you launched wants to return the result to your app, the following occurs:

    • Android creates a new OS process for your app (because it killed yours and needs a new one)
    • Android instantiates the Application instance (or your app's custom one) and calls onCreate() on that
    • Android instantiates a new instance of the Activity that will get the result (the one that called startActivityForResult())
    • Android calls onCreate() on the new Activity. The Bundle passed to onCreate() in this case is the Bundle most recently used to the save the Activity instance state (from onSaveInstanceState()).
    • Android calls onStart() on the new Activity
    • Android calls onActivityResult() on the new Activity
    • Android calls onResume() on the new Activity