个人练习:查看,获取联系人电话
1.main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText
android:id="@+id/show"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:editable="false"
android:cursorVisible="false"
/>
<EditText
android:id="@+id/phone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:editable="false"
android:cursorVisible="false"
/>
<Button
android:id="@+id/btnClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="查看联系人"
/>
</LinearLayout>
2.MainActivity.java
public class MainActivity extends Activity
{
protected static final String TAG = "Click.Button";
protected static final int PICK_CONTACT = 0;
private Button btnClic = null;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnClic = (Button) findViewById(R.id.btnClick);
btnClic.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("vnd.android.cursor.item/phone");
startActivityForResult(intent, PICK_CONTACT);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode)
{
case PICK_CONTACT:
if (resultCode == Activity.RESULT_OK)
{
// 获取返回的数据
Uri contactData = data.getData();
// 查询联系人信息
Cursor cursor = managedQuery(contactData, null, null, null,
null);
// 如果查询到指定的联系人
if (cursor.moveToFirst())
{
String contactID = cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts._ID));
// 获取联系人的姓名
// String name =
// cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String name = cursor
.getString(cursor
.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
String phoneNumber = "此联系人未输入电话号码";
// 根据联系人查询该联系人的详细信息
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ "=" + contactID, null, null);
// 取出第一行
if (phones.moveToFirst())
{
phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
//关闭游标
phones.close();
EditText show = (EditText)findViewById(R.id.show);
show.setText(name);
EditText phone = (EditText)findViewById(R.id.phone);
phone.setText(phoneNumber);
}
cursor.close();
}
break;
}
}
}
3.manifest.xml文件中添加此节点
<uses-permission android:name="android.permission.READ_CONTACTS" />
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步