Bootstrap

android手机获取联系人姓名和电话号码

鉴于电话号码和联系人名保存在adroid手机数据库表中不是同一个表,需要分别从两个表中,通过唯一性的主键"_id"来分别获取,特写下以下是代码示例:

package com.example.androidcontactspeoper;


import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.provider.ContactsContract;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
Button btn = null;
TextView tv = null;
TextView tv2 = null;
String contactId;
static final int requestCodeConstant = 100;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

tv = (TextView) findViewById(R.id.textView1);
tv2 = (TextView) findViewById(R.id.textView2);
btn = (Button) findViewById(R.id.button1);

btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Uri uri = Uri.parse("content://contacts/people");
Intent intent = new Intent(Intent.ACTION_PICK, uri);
startActivityForResult(intent, requestCodeConstant);
}
});
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case requestCodeConstant:
final Uri uriRet = data.getData();
if (uriRet != null) {
try {
Cursor cursor = getContentResolver().query(uriRet, null,
null, null, null);
cursor.moveToFirst();
String name = cursor
.getString(cursor
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
contactId = cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts._ID));
tv.setText("姓名:" + name);
} catch (Exception e) {
e.printStackTrace();
tv.setText(e.toString());
}
}
break;
}
switch (requestCode) {
case requestCodeConstant:
final Uri uriRet = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
if (uriRet != null) {
try {
Cursor cursor = getContentResolver().query(
uriRet,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ "=" + contactId, null, null);
cursor.moveToFirst();
String phoneNumber = cursor
.getString(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER));
tv2.setText("号码:" + phoneNumber);
} catch (Exception e) {
e.printStackTrace();
tv2.setText(e.toString());
}
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
}

以下是演示效果:


;