安卓(android)读取手机通讯录【Android移动开发基础案例教程(第2版)黑马程序员】

news/2025/2/4 8:12:07/

一、实验目的(如果代码有错漏,可在代码地址查看)

1.熟悉内容提供者(Content Provider)的概念和作用。

2.掌握内容提供者的创建和使用方法。

4.掌握内容URI的结构和用途。

二、实验条件

1.熟悉内容提供者的工作原理。

2.掌握内容提供者访问其他应用程序数据的方式。

三、实验内容

1.创建程序,添加recyclerview库。

2.添加界面控件,取消默认标题栏。

3.搭建通讯录列表条目界面布局。

4.封装联系人信息实体类。

5.编写通讯录列表的适配器。

6.实现显示通讯录界面数据的功能。

7.添加读取系统通讯录的权限,运行程序。

四、实验指导

正在layout包下:

1.activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"tools:context=".MainActivity"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Hello World!"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent" /></androidx.constraintlayout.widget.ConstraintLayout>

2.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"><TextViewandroid: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.RecyclerViewandroid:id="@+id/rv_contact"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_margin="2dp"android:background="#F2F4E2"/>
</LinearLayout>

3.contact_item

<?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"><ImageViewandroid:id="@+id/iv_photo"android:layout_width="60dp"android:layout_height="60dp"android:layout_centerVertical="true"app:srcCompat="@drawable/user" /><TextViewandroid: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="李雷" /><TextViewandroid: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="13520677894" />
</RelativeLayout>

Java代码:

package cn.itcast.contacts;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.widget.Toast;import java.util.ArrayList;
import java.util.List;public class ContactActivity extends AppCompatActivity {private RecyclerView recyclerView;@SuppressLint("MissingInflatedId")@Overrideprotected 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();}}@Overridepublic 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() ) {@SuppressLint("Range") String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));@SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));@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);@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;}
}
package cn.itcast.contacts;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@Overridepublic MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {MyViewHolder holder = new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.contact_item,parent,false));return holder;}@Overridepublic 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());}@Overridepublic 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);}}
}
package cn.itcast.contacts;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;}
}

package cn.itcast.contacts;import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}
}

五:代码下载地址:

android: 实现注册界面、实现注册界面、饭堂小广播、音乐播放器、记事本、读取手机通讯录、学生管理系统 - Gitee.com


http://www.ppmy.cn/news/1569179.html

相关文章

Android学习19 -- 手搓App

1 前言 之前工作中&#xff0c;很多时候要搞一个简单的app去验证底层功能&#xff0c;Android studio又过于重型&#xff0c;之前折腾gradle堪称噩梦。所以搞app都只有找应用的同事帮忙。一直想知道一些简单的app怎么能手搓一下&#xff0c;简单快速的搞出来。趁着现在有时间&…

Kamailio、MySQL、Redis、Gin后端、Vue.js前端等基于容器化部署

基于容器化的部署方案&#xff0c;通常会将每个核心服务&#xff08;如Kamailio、MySQL、Redis、Gin后端、Vue.js前端等&#xff09;独立运行在不同的容器中&#xff0c;通过Docker或Kubernetes统一管理。以下是具体实现方式和关键原因&#xff1a; 1. 容器化部署的核心思路 每…

【Linux系统】—— make/makefile

【Linux系统】—— make/makefile 1 什么是 make/makefile2 第一版本makefile3 依赖关系和依赖方法4 清理4.1 清理的基本语法4.2 make 的默认执行4.3 为什么要加 『.PHONY:clean』4.3.1 『.PHONY:clean』的功能4.3.2 如何理解总是不被执行4.3.2 如何区分文件的新旧 5 第二版本m…

Java | CompletableFuture详解

关注&#xff1a;CodingTechWork CompletableFuture 概述 介绍 CompletableFuture是 Java 8 引入的一个非常强大的类&#xff0c;属于 java.util.concurrent 包。它是用于异步编程的一个工具&#xff0c;可以帮助我们更方便地处理并发任务。与传统的线程池或 Future 对比&…

C#魔法秘籍:委托与事件,开启多态回调与消息派对之旅

一、引言&#xff1a;踏入 C# 魔法世界 嘿&#xff0c;各位编程小伙伴们&#xff01;欢迎来到 C# 的奇幻世界&#xff0c;今天我们要一起探索两个超级有趣又强大的特性 —— 委托&#xff08;Delegate&#xff09;和事件&#xff08;Event&#xff09;。这两个家伙可是 C# 编程…

跨平台文件互传工具

一款高效便捷的文件互传工具&#xff0c;支持在线快速传输各种文件格式&#xff0c;无需注册&#xff0c;直接分享文件。适用于个人和团队间的文件共享&#xff0c;跨平台支持&#xff0c;轻松解决文件传输问题。免费的文件传输服务&#xff0c;让你的工作更高效。 gotool

redis原理之数据结构

dict dict&#xff0c;哈希表&#xff0c;redis 所有的 key-value 都存储在里面。如果曾经学过哈希表这种数据结构&#xff0c;那么很容易能写出一个来&#xff0c;但 redis dict 考虑了更多的功能。 // 哈希表&#xff08;字典&#xff09;数据结构&#xff0c;redis 的所有键…

3、从langchain到rag

文章目录 本文介绍向量和向量数据库向量向量数据库 索引开始动手实现rag加载文档数据并建立索引将向量存放到向量数据库中检索生成构成一条链 本文介绍 从本节开始&#xff0c;有了上一节的langchain基础学习&#xff0c;接下来使用langchain实现一个rag应用&#xff0c;并稍微…