androidandroid-intentandroid-jetpack-compose

How to trigger onResult when getting back from Gmail app?


I'm looking for a solution to open the Gmail app to view the inbox in Jetpack Compose, and when I get back, perform some logic. Here is what I have tried:

I have created this launcher:

val gmailAppLauncher = rememberLauncherForActivityResult(
    contract = ActivityResultContracts.StartActivityForResult(),
    onResult = { result ->
        Log.d(TAG, "code: ${result.resultCode}")
    }
)

On button click I use:

onClick = {
    val intent = Intent(Intent.ACTION_MAIN).apply {
        addCategory(Intent.CATEGORY_APP_EMAIL)
        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    }
    gmailAppLauncher.launch(intent)
}

This code opens the Gmail app but it triggers the onResult when I leave my app, not when I return from the Gmail app. The error is:

code: 0

When I click back in the Gmail app, I get back to my app but the onResult is not called anymore. How to solve this issue?


Solution

  • ActivityResultContracts.StartActivityForResult() only works reliably for activities within your app or activities that explicitly return a result. However, the reality is that most third-party apps (including gmail at the time of this answer) don't return results, so you can't get a guaranteed callback when the user comes back to the application.

    Your best bet might be to add a logic that uses lifecycle awareness to determine when the user returns to your app from gmail. But even that option will not expose a success/failure state.