您如何获得Android的主要电子邮件地址(或电子邮件地址列表)?
据我了解,在OS 2.0+上支持多个电子邮件地址,但在2.0以下,每个设备只能有一个电子邮件地址。
您如何获得Android的主要电子邮件地址(或电子邮件地址列表)?
据我了解,在OS 2.0+上支持多个电子邮件地址,但在2.0以下,每个设备只能有一个电子邮件地址。
Answers:
有几种方法可以做到这一点,如下所示。
作为友好的警告,在处理客户,个人资料和联系方式数据时,请格外小心并提前告知用户。如果您滥用用户的电子邮件地址或其他个人信息,可能会发生不良情况。
您可以使用AccountManager.getAccounts
或AccountManager.getAccountsByType
获取设备上所有帐户名称的列表。幸运的是,对于某些帐户类型(包括com.google
),帐户名是电子邮件地址。下面的示例代码段。
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;
...
}
}
请注意,这需要获得GET_ACCOUNTS
许可:
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
有关使用的更多信息,请AccountManager
参见SDK 中的Contact Manager示例代码。
从Android 4.0(Ice Cream Sandwich)开始,您可以通过访问其个人资料来获取用户的电子邮件地址。访问用户个人资料有点繁重,因为它需要两个权限(下面有更多内容),但是电子邮件地址是相当敏感的数据,因此这是允许的费用。
以下是一个完整的示例,该示例使用CursorLoader
来检索包含电子邮件地址的个人资料数据行。
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;
}
}
这需要READ_PROFILE
和READ_CONTACTS
权限:
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
cursor.isAfterLast()
始终返回true。任何的想法?
这可能对其他人有用:
使用AccountPicker在没有任何全局权限的情况下获取用户的电子邮件地址,并允许用户知道并授权或取消该过程。
我将使用ICS中引入的Android的AccountPicker。
Intent googlePicker = AccountPicker.newChooseAccountIntent(null, null, new String[]{GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE}, true, null, null, null, null);
startActivityForResult(googlePicker, REQUEST_CODE);
然后等待结果:
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;
}
android.permission.GET_ACCOUNTS
定义为“危险”权限(需要运行时请求):developer.android.com/reference/android/…–
有一个Android API,可让用户无需许可即可选择其电子邮件地址。看一下: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);
}
这将显示一个选择器,用户可以在其中选择一个电子邮件地址。结果将在onActivityResult()
可悲的是,这个答案行不通。
我来晚了,但这是内部Android Email应用程序的解决方案,除非内容uri由提供商更改:
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;
}
在Android中这是一件非常棘手的事情,而我还没有做到。但是也许这些链接可以帮助您:
使用此方法:
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 "";
}
请注意,这需要获得GET_ACCOUNTS
许可:
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
然后:
editTextEmailAddress.setText(getUserEmail());
建议的答案将不再起作用,因为从android 8开始施加了新的限制。
此处提供更多信息:https : //developer.android.com/about/versions/oreo/android-8.0-changes.html#aaad
Android已锁定 GET_ACCOUNTS
最近因此某些答案对我不起作用。我在Android 7.0上完成了这项工作,但需要注意的是您的用户必须忍受权限对话框。
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);
}
}
}
在MarshMallow操作系统中工作
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);
}
}
});
将此清单行添加到清单中(获得许可)
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
然后将此代码粘贴到您的活动中
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;
}