android调用系统通讯录并返回联系人
1.获取系统通讯录中联系人信息,可以内容提供者来获取到联系人,自定义适配器来显示获取的数据,并显示出来,但我们有时可以直接访问系统联系人并返回联系人的信息,这样即方便,操作起来代码也很少。
隐示跳转到系统通讯录界面Intent为 Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI)
基本代码如下:
布局为:两个EditText和一个button按钮
布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/et1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/et2" a
ndroid:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="添加联系人" />
</LinearLayout>
Activity代码:
package com.example.txl;
public class MainActivity extends Activity {
private EditText et1; // 显示姓名
private EditText et2; // 显示号码
private Button btn; // 添加联系人
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(); // 控件初始化
// 按钮点击
btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v)
{
// 跳转到系统的通讯录界面
startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), 0);
}
});
}
private void findViewById() {
et1 = (EditText) findViewById(R.id.et1);
et2 = (EditText) findViewById(R.id.et2);
btn = (Button) findViewById(R.id.btn);
}
// 返回的数据
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{ // TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
ContentResolver reContentResolverol = getContentResolver();
Uri contactData = data.getData();
@SuppressWarnings("deprecation")
Cursor cursor = managedQuery(contactData, null, null, null, null);
cursor.moveToFirst(); // 获取联系人的姓名
try {
String username = cursor .getString(cursor .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// 获取用户名
String contactId = cursor.getString(cursor .getColumnIndex(ContactsContract.Contacts._ID));
Cursor phone = reContentResolverol.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
while (phone.moveToNext()) {
// 获取联系人号码
String usernumber = phone .getString(phone .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// text.setText(usernumber+" ("+username+")");
et1.setText(usernumber); // 显示返回的号码
et2.setText(username); // 显示返回的联系人姓名
}
}
catch (Exception e) //此处为了防止通讯录提示是否点击禁止而抛出异常
{
et1.setText(""); //设置空
et2.setText("");
}
}
}
}
}
最后别忘记在,AndroidManifest.xml添加下面权限:
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS" />