使用系统自带的ContentProvider查询联系人

//MainActivity.java

package com.example.test_contentproviderdemo;

import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ContentResolver cr = getContentResolver();
        Cursor c = cr.query(Contacts.CONTENT_URI, new String[]{Contacts._ID,Contacts.DISPLAY_NAME}, null, null, null);
        if (c!=null) {
            while (c.moveToNext()) {
                int id = c.getInt(c.getColumnIndex("_id"));
                Log.i("info","_id"+id);
                Log.i("info","name"+c.getString(c.getColumnIndex("display_name")));
                Cursor c1 = cr.query(Phone.CONTENT_URI, new String[]{Phone.NUMBER,Phone.TYPE}, Phone.CONTACT_ID+"="+id, null,null);
                if (c1!=null) {
                    while (c1.moveToNext()) {
                        int type=c1.getInt(c1.getColumnIndex(Phone.TYPE));
                        if (type==Phone.TYPE_HOME) {
                            Log.i("info","家庭电话:"+c1.getString(c1.getColumnIndex(Phone.NUMBER)));
                        }else{
                            Log.i("info","移动电话:"+c1.getString(c1.getColumnIndex(Phone.NUMBER)));
                        }
                    }
                    c1.close();
                }
            }
            c.close();
        }
    }

}

//要在AndroidManifest文件中添加权限

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

PS:
我们是根据联系人的id进行查询号码,不是根据名字进行查询,因为名字有可能相同,但是id是唯一的。

你可能感兴趣的:(android开发)