android开发之内容提供者

一个获取手机联系人小Demo
布局文件如下

<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context="com.cn.yllen.contentprovider.MainActivity">
<ListView
android:id="@+id/conent_view"
android:layout_width="match_parent"
android:layout_height="match_parent"></ListView>
</LinearLayout>

加入权限申明

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

实现代码如下

import android.database.Cursor;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
List<String> contactsList = new ArrayList<>();
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView view = (ListView) findViewById(R.id.conent_view);
adapter = new ArrayAdapter(this,android.R.layout.simple_expandable_list_item_1,contactsList);
view.setAdapter(adapter);
readContacts();
}
private void readContacts()
{
Cursor cursor = null;
try
{
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null,null);
if (cursor != null)
{
while(cursor.moveToNext())
{
//联系人
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
//手机号
String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactsList.add(displayName + "\n" + number);
}
adapter.notifyDataSetChanged();
}
}catch (Exception e)
{
e.printStackTrace();
}finally {
if (cursor != null)
cursor.close();
}
}
}