gpt4 book ai didi

android - 使用 ContentProvider 从联系人获取电话号码 - Android

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:36:29 25 4
gpt4 key购买 nike

我正在制作一个小应用程序,我可以在其中使用内容提供程序获取我手机的联系人,并将它们显示在 ListView 中,如图所示。

enter image description here

我想选择 ListView 的一行并自动调用该特定联系人的电话。我尝试了一些东西,但它们不起作用。有任何想法吗?这是我的代码。

public class MainActivity extends ListActivity implements AdapterView.OnItemClickListener{
ArrayAdapter<String> adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

ContentResolver cr = getContentResolver();
Cursor c = cr.query(ContactsContract.Contacts.CONTENT_URI,
new String[] {ContactsContract.Contacts.DISPLAY_NAME},
null, null, null);

List<String> contacts = new ArrayList<String>();
if (c.moveToFirst()) {
do {
contacts.add(c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
} while (c.moveToNext());
}
adapter = new ArrayAdapter<String>(this, R.layout.activity_main, contacts);
setListAdapter(adapter);



}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

//The answer should be inside here.

}
}

最佳答案

首先,确保您已将权限添加到您的 AndroidManifest.xml 文件中:

<uses-permission android:name="android.permission.READ_CONTACTS"/>

更新:在 Android 6 及更高版本上,声明 list 中的权限不够,您必须明确要求用户授予读取联系人的权限,否则,您将获得异常。参见 this answer了解更多详情。

然后你可以像这样遍历你的手机联系人:

Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null); 
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

if (Boolean.parseBoolean(hasPhone)) {
// You know it has a number so now query it like this
Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, null, null);
while (phones.moveToNext()) {
String phoneNumber = phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
}

Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId, null, null);

while (emails.moveToNext()) {
// This would allow you get several email addresses
String emailAddress = emails.getString(
emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
}

emails.close();
}

关于android - 使用 ContentProvider 从联系人获取电话号码 - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33052002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com