基于Android studio的手机联系人信息获取

最近需要做到这么一个功能,获取联系人信息,并且将联系人姓名和电话显示到屏幕上,上网查了很多资料,折腾了很久才做出来,特此写下感想。

代码原理不多讲,度娘一大堆,在贴代码之前想说一下过程中容易忽略的地方:

1.添加运行时权限,很多时候我们往往只在清单里面添加如下权限,然而在android6之后需要添加运行时权限,否则照样无法运行。

 




2.本想通过ImageView设置点击事件,结果出现了问题,还是换成了Button

下面是完整代码:

XML:

 




    

        

        

主活动代码(本人的活动名称为ThirdActivity):

 

package com.example.administrator;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class ThirdActivity extends AppCompatActivity {

    private Button save_user_info;//保留联系人信息
    private EditText user_name;//编辑姓名
    private EditText user_phone;//编辑电话
    private Button getContacts;
    private String username , usernumber;//调用联系人返回姓名和电话
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_third);
        //初始化
        save_user_info = findViewById(R.id.save_user_info);
        user_name = findViewById(R.id.user_name);
        user_phone = findViewById(R.id.user_phone);
        getContacts = findViewById(R.id.getContacts);

        //运行时权限
        if (ContextCompat.checkSelfPermission(ThirdActivity.this, Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(ThirdActivity.this, new String[]{
                    Manifest.permission.READ_CONTACTS}, 1);
        }
        if (ContextCompat.checkSelfPermission(ThirdActivity.this, Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(ThirdActivity.this, new String[]{
                    Manifest.permission.READ_CONTACTS}, 1);
        }
        else {
            getContacts.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //调用选择联系人界面
                    startActivityForResult(new Intent(Intent.ACTION_PICK,
                            ContactsContract.Contacts.CONTENT_URI), 0);
                }
            });
        }


        //点击保存信息
        save_user_info.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String helper_name = user_name.getText().toString();
                String helper_phone = user_phone.getText().toString();
                if (helper_name.isEmpty()&& helper_phone.isEmpty()){
                    Toast.makeText(ThirdActivity.this,"联系人信息不能为空",Toast.LENGTH_SHORT).show();
                }
                else {
                    Intent intent = new Intent(ThirdActivity.this,ForthActivity.class);
                    intent.putExtra("helper_name",helper_name);
                    intent.putExtra("helper_phone",helper_phone);
                    startActivity(intent);
                    finish();
                }
            }
        });
    }

    //调用联系人信息,返回姓名和电话,显示在EditText中
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            // ContentProvider展示数据类似一个单个数据库表
            // ContentResolver实例带的方法可实现找到指定的ContentProvider并获取到ContentProvider的数据
            ContentResolver reContentResolverol = getContentResolver();
            // URI,每个ContentProvider定义一个唯一的公开的URI,用于指定到它的数据集
            Uri contactData = data.getData();
            // 查询就是输入URI等参数,其中URI是必须的,其他是可选的,如果系统能找到URI对应的ContentProvider将返回一个Cursor对象.
            Cursor cursor = managedQuery(contactData, null, null, null, null);
            cursor.moveToFirst();
            // 获得DATA表中的名字
            username = cursor.getString(cursor
                    .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            // 条件为联系人ID
            String contactId = cursor.getString(cursor
                    .getColumnIndex(ContactsContract.Contacts._ID));
            // 获得DATA表中的电话号码,条件为联系人ID,因为手机号码可能会有多个
            Cursor phone = reContentResolverol.query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "
                            + contactId, null, null);
            while (phone.moveToNext()) {
                usernumber = phone
                        .getString(phone
                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                //显示信息
                user_name.setText(username);
                user_phone.setText(usernumber);
            }
        }
    }
}

亲测可用,欢迎指正和交流!

你可能感兴趣的:(Android)