How to Implement Google Logout when signing in with Google Login

Let’s say that your app has Google Login as the primary mode of authentication. Okay, but how do we let the users log out?

Google actually has a pretty good documentation here on how to implement Google Login in Android apps. You can pretty much copy-paste the code they provide to implement Google Login. But, just like many documentation in the Android community, it doesn’t have any information on logging out users. In this post, I’ll go over how to implement the log out function if your primary mode of user authentication in your app is with Google Login.

For the sake of simplicity, let’s say that the user using your app is already signed in. And let’s also say that you have a log out button somewhere in your app. Here’s the XML for the button itself and an activity that interacts with the button.


Our Activity

To log out of the app, we need to an instance of the GoogleApiClient, just like the one we have to instantiate when implementing the sign in portion of the Google Login. Then we need to use the instance of the GoogleApiClient in order to sign out successfully. To keep this post straightforward, the code for doing all of this is below continuing in the MainActivity.

Let’s go over the code above. It’s pretty straightforward for the most part. We instantiate a GoogleApiClient, add a onClickListener on our logout button, and when the logout button is clicked, we log out the user.

Only tricky part I’ve encountered when trying to log out the user is the connectivity status of the GoogleApiClient. We cannot log out the user unless the GoogleApiClient is connected, the state of which seems to be inconsistent. Sometimes it’s connected and sometimes it’s not. And if the client is not connected, log out will fail.

To consistently log out the user, what we do in our code is to check the connectivity status of the GoogleApiClient by calling isConnected() on it and if it’s connected, sign out the user and launch the LoginActivity and if not, manually connect the GoogleApiClient and sign out the user once it’s connected.

I hope that this post is helpful for those implementing this same exact feature.

About the Author Chris Jeon

Software developer currently focusing on Android development.