安卓基础之读取联系人的姓名和电话

 

一.摘要:利用内容解释器调用联系人应用的内容提供者暴露的方法,读取联系人信息.(本节只总结实现步骤,解释请看http://www.xuanyusong.com/archives/169)

 

二.主要逻辑:

1.获取内容解释者mResolver

ContentResolver mResolver=getApplicationContext().getContentResolver();

2.调用解释者的query方法获取cursor

Cursor cursor=mResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,projection,null,null,null);

3.遍历cursor获得联系人信息

if(cursor!=null){
            while(cursor.moveToNext()){
          ......  
            }
        }

 

三.具体实现:

 

AndroidManifest需要加入权限:

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

 

MainActivity.java

public class MainActivity extends AppCompatActivity {

    String[] projection=new String[]{ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
                                        ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                                        ContactsContract.CommonDataKinds.Phone.NUMBER};

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

        List<Contract> mContracts=new ArrayList<Contract>();
        mContracts=getcontract();
        if(mContracts!=null){
            for (Contract contract:mContracts) {
                int id=contract.getId();
                String name=contract.getName();
                String phone=contract.getPhone();
                System.out.println(id+name+phone);
            }}
    }
    private List<Contract> getcontract(){

        List<Contract> contracts=new ArrayList<Contract>();

        ContentResolver mResolver=getApplicationContext().getContentResolver();
        Cursor cursor=mResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,projection,null,null,null);
        if(cursor!=null){
            while(cursor.moveToNext()){
                String phone =cursor.getString(2);
                int id=cursor.getInt(0);
                String name=cursor.getString(1);
                Contract contract=new Contract();
                contract.setId(id);
                contract.setName(name);
                contract.setPhone(phone);
                contracts.add(contract);
            }
        }
        return contracts;
    }
}

 

Contract.java

public class Contract {
    int id=0;
    String name=null;
    String phone=null;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }


}

 

安卓基础之读取联系人的姓名和电话

上一篇:移动云Mas发送普通短信和模板短信


下一篇:java笔试题(1)