Android 获得通讯录并展示

发布时间:2024年01月25日
ContactActivity.java
package com.ai.b;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class ContactActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact);
        init();
    }
    private void init() {
        recyclerView = findViewById(R.id.rv_contact);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        getPermissions();
    }
    String[] permissionList;

    //申请权限
    public void getPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            permissionList = new String[]{"android.permission.READ_CONTACTS"};
            ArrayList<String> list = new ArrayList<>();
            for (String s : permissionList) {
                if (ActivityCompat.checkSelfPermission(ContactActivity.this, s) !=
                        PackageManager.PERMISSION_GRANTED) {
                    list.add(s);
                }
            }
            if (list.size() > 0) {
                ActivityCompat.requestPermissions(ContactActivity.this, list.toArray(list.toArray(new String[list.size()])),1);
            } else {
                setDate();
            }
        } else {
            setDate();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            for (int i = 0; i < permissions.length; i ++) {
                if(permissions[i].equals("android.permission.READ_CONTACTS") &&
                        grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "读取通讯录权限申请成功", Toast.LENGTH_SHORT).show();
                    setDate();
                } else {
                    Toast.makeText(this, "读取通讯录权限申请失败", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
    private void setDate() {
        List<ContactInfo> contactInfoList = getContacts();
        ContactAdapter adapter = new ContactAdapter(ContactActivity.this , contactInfoList);
        recyclerView.setAdapter(adapter);
    }
    //获取通讯录数据
    private List<ContactInfo> getContacts() {
        List<ContactInfo> contactInfos = new ArrayList<>();
        Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
                null,null,null,null);
        while ( cursor.moveToNext() ) {
            Log.i("c", "0103-01-"+cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            @SuppressLint("Range") String id = cursor.getString(
                    cursor.getColumnIndex(ContactsContract.Contacts._ID));
            @SuppressLint("Range") String name = cursor.getString(
                    cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            Log.i("c", "0103-02-"+ContactsContract.Contacts.CONTENT_URI);
            @SuppressLint("Range") int isHas = cursor.getInt(
                    cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
            if (isHas > 0) {
                Cursor cursor1 = getContentResolver().query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + id,
                        null, null);
                while (cursor1.moveToNext()) {
                    ContactInfo contactInfo = new ContactInfo();
                    contactInfo.setContactName(name);
                    Log.i("c", "0103-03-"+name);
                    @SuppressLint("Range") String number = cursor1.getString(
                            cursor1.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).trim();
                    number = number.replace(" ","");
                    number = number.replace("-","");
                    contactInfo.setPhoneNumber(number);
                    contactInfos.add(contactInfo);
                }
                cursor1.close();
            }
        }
        cursor.close();
        return contactInfos;
    }
}
ContactAdapter.java
package com.ai.b;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;

public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.MyViewHolder> {
    private Context context;
    private List<ContactInfo> contactInfoList;


    public ContactAdapter(Context context, List<ContactInfo> contactInfoList) {
        this.context = context;
        this.contactInfoList = contactInfoList;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        MyViewHolder holder = new MyViewHolder(
                LayoutInflater.from(context).inflate(
                        R.layout.contact_item,parent,false));
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        holder.tv_name.setText((CharSequence) contactInfoList.get(position).getContactName());
        holder.tv_phone.setText((CharSequence) contactInfoList.get(position).getPhoneNumber());
    }

    @Override
    public int getItemCount() {
        return contactInfoList.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder {
        TextView tv_name, tv_phone;
        ImageView iv_photo;
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            iv_photo = itemView.findViewById(R.id.iv_photo);
            tv_name = itemView.findViewById(R.id.tv_name);
            tv_phone = itemView.findViewById(R.id.tv_phone);
        }
    }
}

ContactInfo.java

package com.ai.b;

public class ContactInfo {
    private String contactName;
    private String phoneNumber;

    public String getContactName() {
        return contactName;
    }

    public void setContactName(String contactName) {
        this.contactName = contactName;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }
}

activity_contact.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".ContactActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="center"
        android:padding="5dp"
        android:background="#BFDC9E"
        android:textSize="20sp"
        android:textColor="@color/black"
        android:text="通讯录" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv_contact"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="2dp"
        android:background="#F2F4E2"/>
</LinearLayout>

contact_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:padding="8dp"
    android:background="@drawable/item_bg">

    <ImageView
        android:id="@+id/iv_photo"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_centerVertical="true"
         />

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/iv_photo"
        android:layout_marginTop="5dp"
        android:layout_toEndOf="@+id/iv_photo"
        android:layout_marginStart="20dp"
        android:textColor="@color/black"
        android:text="张三" />

    <TextView
        android:id="@+id/tv_phone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/iv_photo"
        android:layout_marginBottom="5dp"
        android:layout_toEndOf="@+id/iv_photo"
        android:layout_marginStart="20dp"
        android:textColor="@color/black"
        android:text="18800000000" />
</RelativeLayout>

文章来源:https://blog.csdn.net/u013227399/article/details/135826439
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。