选择用于保存联系人的帐户

Selecting an account for saving contacts

我正在申请 phone 图书申请。

我可以看到一些联系人有不同的 ACCOUNT_TYPE_AND_DATA_SET (com.whatsapp, com.viber.voip, com.google, com.android.huawei.sim、com.android.huawei.phone 等)。

问题来了:如何获取可用的帐户列表(权限)来保存联系人?

您可以为此使用 AccountManager 服务:

Account[] accounts = AccountManager.get(this).getAccounts();
for (Account account : accounts) {
   Log.d(TAG, account.type + " / " + account.name);
}

注意,需要 GET_ACCOUNTS 权限,如果您的目标是 Android M 及以上,您还需要通过 Runtime Permissions 模型向用户请求此权限.

更新

要跳过所有根本不支持联系人的帐户,或支持联系人但只读的帐户(如 Viber 和 Whatsapp):

final SyncAdapterType[] syncs = ContentResolver.getSyncAdapterTypes();
for (SyncAdapterType sync : syncs) {
    Log.d(TAG, "found SyncAdapter: " + sync.accountType);
    if (ContactsContract.AUTHORITY.equals(sync.authority)) {
        Log.d(TAG, "found SyncAdapter that supports contacts: " + sync.accountType);
        if (sync.supportsUploading()) {
            Log.d(TAG, "found SyncAdapter that supports contacts and is not read-only: " + sync.accountType);
            // we'll now get a list of all accounts under that accountType:
            Account[] accounts = AccountManager.get(this).getAccountsByType(sync.accountType);
            for (Account account : accounts) {
               Log.d(TAG, account.type + " / " + account.name);
            }
        }
    }
}

随时探索 SyncAdapterType 中的其他好东西,例如 isUserVisible,您可能也想检查一下。