Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android unable get back from email intent

Tags:

android

kotlin

So in my app I have a button to open gmail so the user can check for a verification code.

I use this code to open gmail:

val intent = Intent(Intent.ACTION_MAIN)
intent.addCategory(Intent.CATEGORY_APP_EMAIL)
try {
    activity?.startActivity(intent)
} catch (e: Exception) {
    activity?.let {
        AlertDialog.Builder(it)
            .setTitle("Email App Not Found")
            .show()
    }
}

It is working great to launch gmail, however what I need is for the back button to come back to my app.

Currently when I hit the back button from gmail it will minimize my app, and then reopening my app just reopens gmail with no way to get back to my app without fully closing and reopening it.

Is there a way to override the back button to get back to my app from gmail?

like image 886
Quinn Avatar asked Nov 17 '25 02:11

Quinn


2 Answers

If you don't want the e-mail app to be opened in the current stack, add this flag:

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
like image 96
Cristan Avatar answered Nov 18 '25 17:11

Cristan


So in my app I have a button to open gmail so the user can check for a verification code

You have an incorrectly-constructed Intent to open an email client. The documentation specifically points out that how you are using CATEGORY_APP_EMAIL is incorrect:

NOTE: This should not be used as the primary key of an Intent, since it will not result in the app launching with the correct action and category. Instead, use this with makeMainSelectorActivity(java.lang.String,java.lang.String) to generate a main Intent with this category in the selector.

If you are trying to start the same activity that the launcher does, you would need an ACTION_MAIN/CATEGORY_LAUNCHER Intent, with a selector Intent that attempts to restrict the choices to email apps.

Is there a way to override the back button to get back to my app from gmail?

Not generally. How an app responds to the system BACK button is up to the developers of that app. It is possible that addressing the Intent problem will improve this behavior as a side effect.

like image 29
CommonsWare Avatar answered Nov 18 '25 15:11

CommonsWare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!