答案 0 :(得分:0)
在你的展示文件中添加以下行。
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
然后使用以下代码在您运行的设备中获取已配置的电子邮件ID。
Kotlin中的代码:
private fun getEmailID() {
val listEmail: ArrayList<String> = arrayListOf()
val emailPattern = Patterns.EMAIL_ADDRESS
val accounts = AccountManager.get(this).accounts
accounts.filter { emailPattern.matcher(it.name).matches() }
.mapTo(listEmail) { it.name }
val arrayAdapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listEmail)
spinnerEmail.adapter = arrayAdapter
}
在Java下面使用:
public String extractAddressFromAccountManager() {
accountList = new ArrayList<>();
Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8
Account[] accounts = AccountManager.get(this).getAccountsByType("com.google");
for (Account account : accounts) {
if (emailPattern.matcher(account.name).matches()) {
accountList.add(account.name);
//return account.name;
}
}
return null;
}
获取权限如下:
private boolean isGetAccountsPermissionAllowed() {
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.GET_ACCOUNTS);
if (result == PackageManager.PERMISSION_GRANTED)
return true;
return false;
}
如果未授权,请使用以下内容获取:
private void requestGetAccountsPermission() {
ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.GET_ACCOUNTS);
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.GET_ACCOUNTS}, GET_ACCOUNTS_PERMISSION_REQUEST_CODE);
}