androidlifecycle

ProcessLifecycleOwner not working when launching with certain activities


I'm using ProcessLifecycleOwner to determine when my application goes into the background.

ProcessLifecycleOwner.get().lifecycle.addObserver(
    object : DefaultLifecycleObserver {
        override fun onStart(owner: LifecycleOwner) {
            super.onStart(owner)
            Log.d("DefaultLifecycleObserver", "onStart")
        }

        override fun onStop(owner: LifecycleOwner) {
            super.onStop(owner)
            Log.d("DefaultLifecycleObserver", "onStop")
        }
    }
)

The code above works as expected except for certain use cases such as when:

Launching the Document Picker

val launcher = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocumentTree()) {
    onViewIntent(MediaViewIntent.SelectDirectoryResponse(it))
}

// ...

launcher.launch(null)

Launching the Settings Activity

val uri: Uri = Uri.fromParts("package", context.packageName, null)
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, uri)
ContextCompat.startActivity(context, intent, null)

On both of the occasions, ProcessLifecycleOwner invokes onStop() when either of those two activities are launched and onStart() when closed. It behaves as if my application is headed to the background when it's still in the foreground.

Why does my app behave as if it went into the background?


Solution

  • It behaves as if my application is headed to the background when it's still in the foreground.

    No, it is in the background.

    You did not write the activity that you are starting via the ActivityResultContracts.OpenDocumentTree contract or the Settings.ACTION_APPLICATION_DETAILS_SETTINGS Intent action. Those are from other apps. When you launch full-screen activities from other apps, your app moves to the background.

    Is the Document Picker and Settings Activity launched in a different process?

    Yes.

    is it possible to configure the intent to launch these in the same process?

    No.