Android - 使用AccountManager /手机所有者的名字和姓氏获取UserData

nik*_*3ro 15 android android-contacts

我想预先填充我的应用程序中的一些字段,以帮助用户在我的应用程序中订阅服务时.

那么我如何获得设备所有者的名字和姓氏.我想使用与Google帐户绑定的默认信息; 到目前为止我得到了这个:

AccountManager am = AccountManager.get(this);
Account[] accounts = am.getAccounts();
for (Account account : accounts) {
    if (account.type.compareTo("com.google") == 0)
    {
        String possibleEmail = account.name;
        // how to get firstname and lastname here?
    }             
}
Run Code Online (Sandbox Code Playgroud)

如果你建议,我愿意采取其他方法 - 只要我能得到所有者的电子邮件,名字和姓氏.

Rob*_*ley 23

冰淇淋三明治中获取此信息很容易,因为Android包含代表设备所有者的个人配置文件 - 此配置文件称为"我"配置文件并存储在ContactsContract.Profile表中.只要您在AndroidManifest.xml中请求READ_PROFILEREAD_CONTACTS权限,就可以从用户的个人资料中读取数据.

与您最相关的字段是Contact 中的DISPLAY_NAME列,可能还有StructuredName字段 - 用户的联系人照片等内容也可用.

有一个Android代码实验室教程,提供了阅读用户配置文件的完整示例,代码的核心位于ListProfileTask.这是一个简略的片段:

Cursor c = activity.getContentResolver().query(ContactsContract.Profile.CONTENT_URI, null, null, null, null);
int count = c.getCount();
String[] columnNames = c.getColumnNames();
boolean b = c.moveToFirst();
int position = c.getPosition();
if (count == 1 && position == 0) {
    for (int j = 0; j < columnNames.length; j++) {
        String columnName = columnNames[j];
        String columnValue = c.getString(c.getColumnIndex(columnName)));
        ...
        // consume the values here
    }
}
c.close();
Run Code Online (Sandbox Code Playgroud)

不幸的是,我认为在API级别14之前没有办法获得这种数据.

  • @ gcl1确实没有保证,这就是为什么如果您的个人资料不是SET,您需要从客户经理那里获取名称. (2认同)