Android中通过ContentProvider来获取系统联系人

需要注意的是,要想获取系统联系人,首先应在AndroidManifest中获取读取联系人权限,即添加如下代码:

     
     

如果使用模拟器运行时,需要先在模拟器里面添加一些联系人,手机运行的话,如果有联系人就不需要添加了,否则也需要添加。

MainActivity代码如下:

import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;


public class MainActivity extends Activity implements OnClickListener {
private Button btn;
private ListView listView;
private Cursor cursor1, cursor2;
private ContentResolver resolver;
private List list;
private Person person;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn);
listView = (ListView) findViewById(R.id.listView);
resolver = getContentResolver();
btn.setOnClickListener(this);
list = new ArrayList();


}


@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.btn) {
cursor1 = resolver.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
while (cursor1.moveToNext()) {
person = new Person();
String id = cursor1.getString(cursor1
.getColumnIndex(ContactsContract.Contacts._ID));
String name1 = cursor1
.getString(cursor1
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
person.setName(name1);
cursor2 = resolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ "=" + id, null, null);
while (cursor2.moveToNext()) {
String number1 = cursor2
.getString(cursor2
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
person.setNumber(number1);
}
list.add(person);
}
listView.setAdapter(new MyBaseAdapter(list, MainActivity.this));
}
}
}

activity_main布局如下:

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >


   

你可能感兴趣的:(Android中通过ContentProvider来获取系统联系人)