说三道四技术文摘-感悟人生的经典句子
说三道四 > 文档快照

获得手机中的电话簿

HTML文档下载 WORD文档下载 PDF文档下载
有时您可能想备份电话簿。这个功能很常见。不过如何自己编程来获取呢?本人买了一本《Android应用开发揭密》,这本书挺好。就是里面的便子有点老了。书中第34页关于获得电话本的方法有误:只能获取联系人,却不能获得电话号码。我猜可能因为该书的代码是基于Android1.6的吧?通过多方查找资料,并且反复调试,我找到了正确的方法。
首先,要在AndroidManifest.xml中,添加以下的权限说明。<uses-permission android:name="android.permission.READ_CONTACTS">    </uses-permission>代码如下:

 

<uses-permission android:name="android.permission.READ_CONTACTS">
    </uses-permission>
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.main); TextView tv = new TextView(this); String sAll = "---电话列表---by dxm \n"; // 得到ContentResolver对象] ContentResolver cr = getContentResolver(); Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null); while(cursor.moveToNext()) { int nIndex = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME); String sName = cursor.getString(nIndex); Log.e("MYTAG",sName); int nIndex2 = cursor.getColumnIndex(PhoneLookup.HAS_PHONE_NUMBER); String sTmp=""; sTmp += nIndex2; String sHasNumber = cursor.getString(nIndex2); sAll += (sName + ":"); Log.e("MYTAG","hasNumber:"+sHasNumber); if( sHasNumber.compareTo("1")==0) { int idFieldIndex=cursor.getColumnIndex(ContactsContract.Contacts._ID); int id=cursor.getInt(idFieldIndex); Cursor phones = cr.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + "?", new String[]{Integer.toString(id)}, null); while (phones.moveToNext()) { String sNumber = "NONE"; nIndex = phones .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER); sNumber = phones.getString(nIndex); Log.e("MYTAG",sNumber); nIndex = phones .getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE); String sType = phones.getString(nIndex); sAll+= (sNumber + ":" + sType + "\n"); } Log.e("MYTAG","OH"); } else { sAll+= ("no phone number \n"); } } cursor.close(); tv.setText(sAll); setContentView(tv); }

 

 

备案号:鲁ICP备13029499号-2 说三道四 www.s3d4.cn 说三道四技术文摘