How to get the Android device's primary e-mail address
How do you get the Android's primary e-mail addres开发者_运维问答s (or a list of e-mail addresses)?
It's my understanding that on OS 2.0+ there's support for multiple e-mail addresses, but below 2.0 you can only have one e-mail address per device.
There are several ways to do this, shown below.
As a friendly warning, be careful and up-front to the user when dealing with account, profile, and contact data. If you misuse a user's email address or other personal information, bad things can happen.
Method A: Use AccountManager (API level 5+)
You can use AccountManager.getAccounts
or AccountManager.getAccountsByType
to get a list of all account names on the device. Fortunately, for certain account types (including com.google
), the account names are email addresses. Example snippet below.
Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
Account[] accounts = AccountManager.get(context).getAccounts();
for (Account account : accounts) {
if (emailPattern.matcher(account.name).matches()) {
String possibleEmail = account.name;
...
}
}
Note that this requires the GET_ACCOUNTS
permission:
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
More on using AccountManager
can be found at the Contact Manager sample code in the SDK.
Method B: Use ContactsContract.Profile (API level 14+)
As of Android 4.0 (Ice Cream Sandwich), you can get the user's email addresses by accessing their profile. Accessing the user profile is a bit heavyweight as it requires two permissions (more on that below), but email addresses are fairly sensitive pieces of data, so this is the price of admission.
Below is a full example that uses a CursorLoader
to retrieve profile data rows containing email addresses.
public class ExampleActivity extends Activity implements LoaderManager.LoaderCallbacks<Cursor> {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getLoaderManager().initLoader(0, null, this);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle arguments) {
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath(
ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY),
ProfileQuery.PROJECTION,
// Select only email addresses.
ContactsContract.Contacts.Data.MIMETYPE + " = ?",
new String[]{ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE},
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
List<String> emails = new ArrayList<String>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
emails.add(cursor.getString(ProfileQuery.ADDRESS));
// Potentially filter on ProfileQuery.IS_PRIMARY
cursor.moveToNext();
}
...
}
@Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
}
private interface ProfileQuery {
String[] PROJECTION = {
ContactsContract.CommonDataKinds.Email.ADDRESS,
ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
};
int ADDRESS = 0;
int IS_PRIMARY = 1;
}
}
This requires both the READ_PROFILE
and READ_CONTACTS
permissions:
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
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.
I would use Android's AccountPicker, introduced in ICS.
Intent googlePicker = AccountPicker.newChooseAccountIntent(null, null, new String[]{GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE}, true, null, null, null, null);
startActivityForResult(googlePicker, REQUEST_CODE);
And then wait for the result:
protected void onActivityResult(final int requestCode, final int resultCode,
final Intent data) {
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
}
}
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;
}
There is an Android api that allows the user to select their email address without the need for a permission. Take a look at: https://developers.google.com/identity/smartlock-passwords/android/retrieve-hints
HintRequest hintRequest = new HintRequest.Builder()
.setHintPickerConfig(new CredentialPickerConfig.Builder()
.setShowCancelButton(true)
.build())
.setEmailAddressIdentifierSupported(true)
.setAccountTypes(IdentityProviders.GOOGLE)
.build();
PendingIntent intent = mCredentialsClient.getHintPickerIntent(hintRequest);
try {
startIntentSenderForResult(intent.getIntentSender(), RC_HINT, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
Log.e(TAG, "Could not start hint picker Intent", e);
}
This will show a picker where the user can select an emailaddress. The result will be delivered in onActivityResult()
Sadly accepted answer isn't working.
I'm late, but here's the solution for internal Android Email application unless the content uri is changed by provider:
Uri EMAIL_ACCOUNTS_DATABASE_CONTENT_URI =
Uri.parse("content://com.android.email.provider/account");
public ArrayList<String> GET_EMAIL_ADDRESSES ()
{
ArrayList<String> names = new ArrayList<String>();
ContentResolver cr = m_context.getContentResolver();
Cursor cursor = cr.query(EMAIL_ACCOUNTS_DATABASE_CONTENT_URI ,null,
null, null, null);
if (cursor == null) {
Log.e("TEST", "Cannot access email accounts database");
return null;
}
if (cursor.getCount() <= 0) {
Log.e("TEST", "No accounts");
return null;
}
while (cursor.moveToNext()) {
names.add(cursor.getString(cursor.getColumnIndex("emailAddress")));
Log.i("TEST", cursor.getString(cursor.getColumnIndex("emailAddress")));
}
return names;
}
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+
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());
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;
}
The suggested answers won't work anymore as there is a new restriction imposed from android 8 onwards.
more info here: https://developer.android.com/about/versions/oreo/android-8.0-changes.html#aaad
For Android 8 and above -
Step 1 - Add the following code in AndroidManifest.xml -
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
Step 2 - Add the following code in your activity asking for permissions at runtime.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if ((ActivityCompat.checkSelfPermission(this, Manifest.permission.GET_ACCOUNTS) == PackageManager.PERMISSION_GRANTED) && (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED)) {
getGoogleAccounts();
}
else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.GET_ACCOUNTS, Manifest.permission.READ_CONTACTS}, 1);
//return false;
}
}
Step 3 - Add code for onRequestPermissionsResult -
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
getGoogleAccounts();
}
}
Step 4 - Finally add code to retrieve account using AccountManager
private void getGoogleAccounts(){
AccountManager am = AccountManager.get(this); // "this" references the current Context
Account[] accounts = am.getAccountsByType("com.google");
for (Account acc : accounts){
System.out.println("http accounts " + acc);
}
}
Please refer to following link for changes in android 8 - https://developer.android.com/about/versions/oreo/android-8.0-changes#aaad
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);
}
}
}
Working In MarshMallow Operating System
btn_click=(Button) findViewById(R.id.btn_click);
btn_click.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
int permissionCheck = ContextCompat.checkSelfPermission(PermissionActivity.this,
android.Manifest.permission.CAMERA);
if (permissionCheck == PackageManager.PERMISSION_GRANTED)
{
//showing dialog to select image
String possibleEmail=null;
Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
Account[] accounts = AccountManager.get(PermissionActivity.this).getAccounts();
for (Account account : accounts) {
if (emailPattern.matcher(account.name).matches()) {
possibleEmail = account.name;
Log.e("keshav","possibleEmail"+possibleEmail);
}
}
Log.e("keshav","possibleEmail gjhh->"+possibleEmail);
Log.e("permission", "granted Marshmallow O/S");
} else { ActivityCompat.requestPermissions(PermissionActivity.this,
new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE,
android.Manifest.permission.READ_PHONE_STATE,
Manifest.permission.GET_ACCOUNTS,
android.Manifest.permission.CAMERA}, 1);
}
} else {
// Lower then Marshmallow
String possibleEmail=null;
Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
Account[] accounts = AccountManager.get(PermissionActivity.this).getAccounts();
for (Account account : accounts) {
if (emailPattern.matcher(account.name).matches()) {
possibleEmail = account.name;
Log.e("keshav","possibleEmail"+possibleEmail);
}
Log.e("keshav","possibleEmail gjhh->"+possibleEmail);
}
}
});
精彩评论