阅读 337

Android获取系统邮件账号

android账户取得方法

1. 8.0以下动态申请运行时权限 Manifest.permission.GET_ACCOUNTS

获取权限后取得账户的方法:

你可以用AccountManager.getAccounts or AccountManager.getAccountsByType来获取账户列表

代码如下所示:

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 accountName = account.name;
        String accountType = account.type;
        System.out.println("name:" + accountName + "\n" + "type:" + accountType);
    }
}
复制代码

上面代码略显重复,还可以这样写:

Account[] accounts = AccountManager.get(this).getAccountsByType("com.android.email");
复制代码

注意:AccountManager.getAccounts() 获得手机中所有账户信息,除了邮件账户也包括微博等其他类型的账号。

2. 8.0以上(包含8.0)动态申请运行时权限 Manifest.permission.GET_ACCOUNTS

获取权限后取得账户的方法:

Intent intent = AccountManager.newChooseAccountIntent(null, null, new String[]{"com.android.email"},
                    null, null, null, null);
            startActivityForResult(intent, REQUEST_CODE_PICK_ACCOUNT);



@Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtil.e("lzx","onActivityResult ");
        if (requestCode == REQUEST_CODE_PICK_ACCOUNT && resultCode == RESULT_OK) {
            // Receiving a result from the AccountPicker
            LogUtil.e(TAG,"KEY_ACCOUNT_NAME " + data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME));
            LogUtil.e(TAG,"KEY_ACCOUNT_TYPE " + data.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE));
            Account[] accounts = AccountManager.get(this).getAccountsByType("com.android.email");
            LogUtil.e(TAG,"accounts lenth " + accounts.length );
        }
    }
复制代码

 

 

文章分类
Android
文章标签