onActivityResult: A Few Traps and Pitfalls

Published 3/1/2018, Last Updated 3/1/2018 by Joe Cieslik


Various Infernal Methods

Recently I spent an inordinate amount of time debugging an Android Google authentication flow on a client project. We were using several deprecated APIs including GoogleApiClient which got replaced by the greatly improved GoogleSignInClient. A special shoutout to shoehorning in a singleton instance of the API client and dealing with its eternal connection issues. Wrangling in the new APIs and methods made my life easier and made our codebase cleaner but there was one hiccup.

In the end the final boss was an issue with startActivityForResult. When a user, who wasn't logged into any Google accounts on their device, tapped the Google signin button on our authentication activity they would be redirected to Google's signin flow. This is normally fine but upon completion the user would be spit out at the app drawer instead of back at our authentication activity. I struggled with this bug on and off for a while, taking breaks to work on other pressing issues.

About half way through my struggle with this bug I found this line, android:noHistory="true", in the manifest in the activity element for the activity that preceded the authentication activity. Remove that and success! Suddenly the Google authentication intent brought the user back to our app's activity properly. Unfortunately, our tale of woe doesn't end there because onActivityResult was not being called. It took a bunch of Log.ds sprinkled throughout the activity to pin this down for certain. After much despair and crying out to various cruel deities I checked the utility function that launches the authentication activity. As soon as I laid eyes upon the 3 lines of the function I desperately wanted to do harm to my keyboard and monitor with my forehead. Because the 2nd line was: intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); and I pondered for at least 3 days why I hadn't checked the actual content of that function earlier.

I hope you enjoyed reading my dramatic retelling of this time-consuming issue. I'm trying to add new blog posts of varying content and quality at a more regular interval so stick around.