很简单的一个程序,打印出手机上所有人的姓名和联系电话,这个是通过adb logcat输出到指定的文件的,所以中文不是乱码:
I/System.out(26319): +861865310623 I/System.out(26319): id=36,name=杜倩,phone:+8618653146338 I/System.out(26319): +861870112606 I/System.out(26319): id=37,name=宋飞,phone:+86187617246063 I/System.out(26319): +861340762121 I/System.out(26319): id=38,name=张增阳,phone:+8613402628210 I/System.out(26319): +861866975871 I/System.out(26319): id=39,name=苗灏,phone:+8618649755712 I/System.out(26319): +861521032152 I/System.out(26319): id=40,name=李凌云,phone:+8615810321545 I/System.out(26319): 1345504408 I/System.out(26319): id=142,name=阿杜,phone:13455023080 I/System.out(26319): 1364760537 I/System.out(26319): id=143,name=杜以阳,phone:13645606778 I/System.out(26319): 1356196421 I/System.out(26319): id=144,name=嫂子,phone:13561956784 I/System.out(26319): 1340681488 I/System.out(26319): id=145,name=杜涛,phone:13456712388
代码很简短:
//Get contacts info Cursor cursor=contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); while (cursor.moveToNext()) { int id=cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID)); String name=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); String myPhoneNumber=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)); String phoneNumber=null; if (myPhoneNumber.equals("1")) { Cursor phones=contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID+"="+id, null, null); StringBuffer sb=new StringBuffer(); while (phones.moveToNext()) { phoneNumber=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); sb.append(phoneNumber).append(","); } int index=sb.lastIndexOf(","); String temp=sb.substring(0, index-1); System.out.println(temp); } System.out.println("id="+id+",name="+name+",phone:"+phoneNumber); }
当然在AndroidManifest.xml中要有权限:<uses-permission android:name="android.permission.READ_CONTACTS"/>