android 入门学习笔记 电话簿查询

/*必须引用database.Cursor,Contacts.People 与 net.uri等类来使用联系人数据*/ import android.database.Cursor; import android.net.Uri; import android.provider.Contacts.People;


 

/*建构Uri来取得联系人的资源位置*/ Uri uri = Uri.parse("content://contacts/people"); /*通过Intent来取得联系人数据并返回所选的值*/ Intent intent = new Intent(Intent.ACTION_PICK, uri); /*打开新的Activity并期望该Activity返回值*/ startActivityForResult(intent, PICK_CONTACT_SUBACTIVITY);
@Override protected void onActivityResult (int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub switch (requestCode) { case PICK_CONTACT_SUBACTIVITY: final Uri uriRet = data.getData(); if(uriRet != null) { try { /* 必须要有android.permission.READ_CONTACTS权限 */ Cursor c = managedQuery(uriRet, null, null, null, null); /*将Cursor移到资料最前端*/ c.moveToFirst(); /*取得联系人的姓名*/ String strName = c.getString(c.getColumnIndexOrThrow(People.NAME)); /*取得联系人的电话*/ String strPhone = c.getString(c.getColumnIndexOrThrow(People.NUMBER)); /*将姓名与电话写入EditText01,EditText02中*/ mEditText01.setText(strName); mEditText02.setText(strPhone); } catch(Exception e) { /*将错误信息在TextView中显示*/ mTextView01.setText(e.toString()); e.printStackTrace(); } } break; } super.onActivityResult(requestCode, resultCode, data); }

 

如果只是查询电话簿,需 <uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>

如果需要增加修改删除则需 <uses-permission android:name="android.permission.WRITE_CONTACTS"></uses-permission>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/125bd4e9546a066eac95f0efb60f4f32.html