您的位置:首页 > 移动开发 > Android开发

Android内容提供者(一)读取系统联系人

2016-06-23 13:56 525 查看
想要读取系统的联系人,必须先获取权限。

1.创建工程ReadContacts,在清单文件中添加读取联系人的权限。

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


2.修改主布局,添加用来显示数据的listview

<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" >

<ListView
android:id="@+id/contacts_list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>

</LinearLayout>


3.创建代码,读取系统联系人(如果是模拟器的话,先在联系人中随便添加几个)

public class MainActivity extends Activity {

private ListView mContactsLV;
private ArrayAdapter<String> mAdapter;
private List<String> mContactsList;

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

mContactsLV = (ListView) findViewById(R.id.contacts_list_view);
mContactsList = new ArrayList<String>();
Cursor cursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, null);
while (cursor.moveToNext()) {
String name = cursor
.getString(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number = cursor
.getString(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
mContactsList.add(name + "\n" + number);
}
if (cursor != null) {
cursor.close();
}
mAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, mContactsList);
mContactsLV.setAdapter(mAdapter);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}


运行程序,启动模拟器,就可以看到手机中保存联系人的姓名和电话号码了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 读取联系人