之前做了一个小练习需要用到获取手机里联系人的电话号码,通过查阅相关的资料,自己尝试写了一个小例子,可以成功获取。
首先需要在AndroidManifest.xml中获取权限
xml布局文件
MainActivity.java
package com.getcontacts; import android.net.Uri; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity { Button button; EditText editText; private Uri uri_DATA = Uri.parse("content://com.android.contacts/data"); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.buttonQuary); editText = (EditText) findViewById(R.id.editNumber); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub editText.setText(""); //做跳转之前先把电话号码清空 Intent intent = new Intent(Intent.ACTION_PICK, android.provider.ContactsContract.Contacts.CONTENT_URI); startActivityForResult(intent, 1); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); if(requestCode == 1) { //请求码为1 Log.i("info","resultADD"); String strNumber = ""; if(data != null) { //判断返回的intent是不是为空 Uri uri = data.getData(); Log.i("info", uri.toString()); //在log打印出来获取的uri Cursor cursor = getContentResolver().query(uri, null, null, null, null); while(cursor.moveToNext()) { String strID = cursor.getString(cursor.getColumnIndex("name_raw_contact_id")); Cursor cursor2 = getContentResolver().query(uri_DATA, null, "raw_contact_id = " + strID + " and mimetype_id = 5", null, null); if(cursor2.moveToFirst()) { strNumber = cursor2.getString(cursor2.getColumnIndex("data1")); strNumber = strNumber.replace(" ", ""); strNumber = strNumber.replace("-", ""); } cursor2.close(); } cursor.close(); editText.setText(strNumber); } } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。