如何获取Android设备的主要电子邮件地址
如何获得Android的主要电子邮件地址(或电子邮件地址列表)?
我的理解是,在OS 2.0+上支持多个电子邮件地址,但是在2.0以下,每个设备只能有一个电子邮件地址。
有几种方法可以做到这一点,如下所示。
作为一个友好的警告,在处理帐户,configuration文件和联系人数据时要小心,并向用户提前。 如果您滥用用户的电子邮件地址或其他个人信息,可能会发生不好的事情。
方法A:使用AccountManager (API级别5+)
您可以使用AccountManager.getAccounts
或AccountManager.getAccountsByType
获取设备上所有帐户名称的列表。 幸运的是,对于某些帐户types(包括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中的联系人pipe理器示例代码。
方法B:使用ContactsContract.Profile (API级别14+)
从Android 4.0(冰淇淋三明治),您可以通过访问他们的个人资料获取用户的电子邮件地址。 访问用户configuration文件有点重量级,因为它需要两个权限(下面有更多的权限),但是电子邮件地址是相当敏感的数据,所以这是入场的价格。
以下是使用CursorLoader
检索包含电子邮件地址的configuration文件数据行的完整示例。
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" />
这可能对其他人有用:
使用AccountPicker获取用户的电子邮件地址,没有任何全局权限,并允许用户知道和授权或取消进程。
我会使用Android的AccountPicker ,在ICS中引入。
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中这是相当棘手的事情,我还没有做到这一点。 但是,也许这些链接可能会帮助你:
- Android Issue 1073:Google身份validation令牌应该可以通过API访问第三方应用程序
- Andriod 2.x +中的SDK API AccountManager
可悲的接受的答案是行不通的。
我迟到了,但这里是内部Android电子邮件应用程序的解决scheme,除非内容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; }
在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 {
//降低棉花糖
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); } } });