How to get the Android device's primary e-mail address

后端 未结 12 2305
借酒劲吻你
借酒劲吻你 2020-11-21 13:30

How do you get the Android\'s primary e-mail address (or a list of e-mail addresses)?

It\'s my understanding that on OS 2.0+ there\'s support for multiple e-mail add

相关标签:
12条回答
  • 2020-11-21 13:59

    Android locked down GET_ACCOUNTS recently so some of the answers did not work for me. I got this working on Android 7.0 with the caveat that your users have to endure a permission dialog.

    AndroidManifest.xml

    <uses-permission android:name="android.permission.GET_ACCOUNTS"/>
    

    MainActivity.java

    package com.example.patrick.app2;
    import android.content.pm.PackageManager;
    import android.support.v4.app.ActivityCompat;
    import android.support.v4.content.ContextCompat;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.accounts.AccountManager;
    import android.accounts.Account;
    import android.app.AlertDialog;
    import android.content.DialogInterface;
    import android.content.*;
    
    public class MainActivity extends AppCompatActivity {
    
        final static int requestcode = 4; //arbitrary constant less than 2^16
    
        private static String getEmailId(Context context) {
            AccountManager accountManager = AccountManager.get(context);
            Account[] accounts = accountManager.getAccountsByType("com.google");
            Account account;
            if (accounts.length > 0) {
                account = accounts[0];
            } else {
                return "length is zero";
            }
            return account.name;
        }
    
        @Override
        public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            switch (requestCode) {
                case requestcode:
                    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
    
                        String emailAddr = getEmailId(getApplicationContext());
                        ShowMessage(emailAddr);
    
                    } else {
                        ShowMessage("Permission Denied");
                    }
            }
        }
    
        public void ShowMessage(String email)
        {
            AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
            alertDialog.setTitle("Alert");
            alertDialog.setMessage(email);
            alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            alertDialog.show();
        }
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            Context context = getApplicationContext();
    
            if ( ContextCompat.checkSelfPermission( context, android.Manifest.permission.GET_ACCOUNTS )
                    != PackageManager.PERMISSION_GRANTED )
            {
                ActivityCompat.requestPermissions( this, new String[]
                                {  android.Manifest.permission.GET_ACCOUNTS  },requestcode );
            }
            else
            {
                String possibleEmail = getEmailId(getApplicationContext());
                ShowMessage(possibleEmail);
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-21 14:04

    Use this method:

     public String getUserEmail() {
        AccountManager manager = AccountManager.get(App.getInstance());
        Account[] accounts = manager.getAccountsByType("com.google");
        List<String> possibleEmails = new LinkedList<>();
        for (Account account : accounts) {
            possibleEmails.add(account.name);
        }
        if (!possibleEmails.isEmpty() && possibleEmails.get(0) != null) {
            return possibleEmails.get(0);
        }
        return "";
    }
    

    Note that this requires the GET_ACCOUNTS permission:

    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    

    Then:

    editTextEmailAddress.setText(getUserEmail());
    
    0 讨论(0)
  • 2020-11-21 14:06
    public String getUsername() {
        AccountManager manager = AccountManager.get(this);
        Account[] accounts = manager.getAccountsByType("com.google");
        List<String> possibleEmails = new LinkedList<String>();
    
        for (Account account : accounts) {
            // TODO: Check possibleEmail against an email regex or treat
            // account.name as an email address only for certain account.type values.
            possibleEmails.add(account.name);
        }
    
        if (!possibleEmails.isEmpty() && possibleEmails.get(0) != null) {
            String email = possibleEmails.get(0);
            String[] parts = email.split("@");
    
            if (parts.length > 1)
                return parts[0];
        }
        return null;
    }
    
    0 讨论(0)
  • 2020-11-21 14:06

    This is quite the tricky thing to do in Android and I haven't done it yet. But maybe these links may help you:

    • Android Issue 1073:Google Auth Tokens should be accessible to 3rd party applications through an API
    • SDK API AccountManager in Andriod 2.x+
    0 讨论(0)
  • 2020-11-21 14:06

    Add this single line in manifest (for permission)

    <uses-permission android:name="android.permission.GET_ACCOUNTS" />

    Then paste this code in your activity

    private ArrayList<String> getPrimaryMailId() {
        ArrayList<String> accountsList = new ArrayList<String>();
        try {
            Account[] accounts = AccountManager.get(this).getAccountsByType("com.google");
            for (Account account : accounts) {
                accountsList.add(account.name);
                Log.e("GetPrimaryMailId ", account.name);
            }
        } catch (Exception e) {
            Log.e("GetPrimaryMailId", " Exception : " + e);
        }
        return accountsList;
    }
    
    0 讨论(0)
  • 2020-11-21 14:09

    This could be useful to others:

    Using AccountPicker to get user's email address without any global permissions, and allowing the user to be aware and authorize or cancel the process.

    0 讨论(0)
提交回复
热议问题