For my startup’s app I’m working on, I had to add a log in feature so that we can add more custom features down the line. I realized that the app didn’t have anything particularly sensitive, so we could provide users with a better experience by not having them create a new password or worry about different social medias. Our users are already logged on to their devices with their Google account, and that knowledge can be reused.

Here’s a quick walk-through for the code I’ve added. It assumes a basic understanding of Android and Gradle.

  1. In AndroidManifest.xml, add <uses-permission android:name="ANDROID.PERMISSION.GET_ACCOUNTS"/>
  2. In the project’s build.gradle, add dependency compile 'com.google.android.gms:play-services:8.1.0' (or similar version)
  3. In your Activity or Fragment, add the following code: (Note: I’ve chosen to programmatically create the UI for this sample rather than using XML.)

    public class MainActivity extends Activity {

     private static final int REQUEST_CODE_EMAIL = 100; // Arbitrary unique number.
     private TextView mText;
    
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
    
         LinearLayout rootContent = new LinearLayout(this);
         rootContent.setOrientation(LinearLayout.VERTICAL);
    
         Button getUserEmailButton = new Button(this);
         getUserEmailButton.setText("Get email");
         getUserEmailButton.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 requestUserEmail();
             }
         });
         rootContent.addView(getUserEmailButton);
    
         mText = new TextView(this);
    
         rootContent.addView(mText);
         setContentView(rootContent);
     }
    
     @Override
     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
         if (requestCode == REQUEST_CODE_EMAIL && resultCode == RESULT_OK) {
             String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
             mText.setText(accountName);
         }
     }
    
     private void requestUserEmail() {
         try {
             Intent intent = AccountPicker.newChooseAccountIntent(null, null,
                     new String[]{GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE}, false, null, null, null, null);
             startActivityForResult(intent, REQUEST_CODE_EMAIL);
         } catch (ActivityNotFoundException e) {
             mText.setText("Google Play Services not available");
         }
     }
    

    }

And, that’s it. This sample project’s code is open source on GitHub. Some screenshots are also provided there.

Now a quick word from a tech company who helps support me and this site: