irpas技术客

简单步骤:Android studio 内容提供者 - 实现建立手机通讯录界面,读取系统联系人_蛇形刁手_android studio手机通讯录

大大的周 1536

提示:本篇文章将会尽量保持精简,同时请诸位敲写代码时保持耐心,三连是最大的支持!

文章目录

前言

一、项目介绍

二、使用步骤

1.创建程序

2.添加 recyclerview-v7 库

3.放置界面控件

4.搭建界面布局

5.封装实体类

6.编写数据适配器

7.实现显示界面数据功能

8.去掉默认标题栏,添加读取系统通讯录权限

9.运行程序

总结


前言

本篇文章将会介绍如何使用?Android studio?内容提供者 实现 “读取手机通讯录” 的项目,文章是经由本人实际编写过后得出,同时项目中的名称等如有冲突可自行更改。文章尽量保持精简,也请诸位保持耐心,且会加以图文解释,方便读者能够更佳观看。

配置:Android studio 2021.1.1.21 windows??


一、项目介绍

本项目通过显示一个通讯录的界面,以列表的形式来显示 Android 设备通讯录中暴露的数据, 而 Android 便提供了一个组件 ContentProvider(内容提供者) 来充当一个 “中介” 的角色。具体有关 ContentProvider(内容提供者) 的细节在这就不再赘述。

二、使用步骤 1.创建程序

打开 Android studio,在 Android studio 创建一个新的应用程序,命名为 Contact?,指定包名为 com.itcast.contacts 。

2.添加 recyclerview-v7 库

因为我们通讯录界面将要使用到 RecyclerView 控件,以列表的形式展示,所以需要将拥有? RecyclerView 控件的 recyclerview-v7 库添加进程序。但是由于版本和补丁的更新,我们只需要在 Android 的?Gradle Scripts 下的 build.gradle(Module:Contact.app) 中填入一下代码

代码如下:

dependencies { // 。。。。。 implementation 'androidx.recyclerview:recyclerview:1.0.0' }

更为详细的说明可以移步到:简单步骤:解决 Android studio 2021.1.1 出现添加 “ recyclerview-v7 库 ”报错_蛇形刁手的博客-CSDN博客

3.放置界面控件

在 res/layout 文件夹的 activity_contact.xml 下放置一个 TextView控件 和 RecyclerView 控件来以列表的形式显示通讯录和其中联系人的信息。?

??代码如下:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#eaeaea" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="50dp" android:background="#4889f4" android:gravity="center" android:text="通讯录" android:textColor="@android:color/white" android:textSize="20sp" /> <androidx.recyclerview.widget.RecyclerView android:id="@+id/rv_contact" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="5dp" /> </LinearLayout> 4.搭建界面布局

<1> 在 res/layout 文件夹下,创建布局文件 contact_item.xml , 编写界面控件。

?代码如下:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:background="@drawable/item_bg" android:orientation="horizontal" android:padding="8dp"> <ImageView android:id="@+id/iv_photo" android:layout_width="60dp" android:layout_height="60dp" android:src="@drawable/contact_photo" /> <LinearLayout android:layout_width="match_parent" android:layout_height="60dp" android:layout_marginLeft="8dp" android:gravity="center_vertical" android:orientation="vertical"> <TextView android:id="@+id/tv_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@android:color/black" android:textSize="16sp" /> <TextView android:id="@+id/tv_phone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="6dp" android:textColor="@android:color/darker_gray" android:textSize="14sp" /> </LinearLayout> </LinearLayout>

<2> 导入图片

将通讯录界面所需要的图片 contact_photo.png 导入到 res/drewable?文件夹中。(如果文章会自动生成水印,那么推荐使用自己的图片)

图片如下:

<3> 创建条目界面的背景文件

在res/drewable?文件夹中创建 item_bg.xml文件设置条目背景。

代码如下:

<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#ffffff" /> <corners android:radius="8dp" /> </shape> ?5.封装实体类

在程序的 java/com.itcast.contacts 包下创建一个 ContactInfo 类,用来创建联系人信息的属性。

?代码如下:

package com.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; } } 6.编写数据适配器

在程序的 java/com.itcast.contacts 包下创建一个 ContactAdapter?类,由于我们使用了 RecyclerView 控件,所以就需要创建一个数据适配器,来对 RecyclerView 控件进行数据适配。

?代码如下:

package com.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.recyclerview.widget.RecyclerView; import java.util.List; public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter .MyViewHolder> { private Context mContext; private List<ContactInfo> contactInfoList; public ContactAdapter(Context context, List<ContactInfo> contactInfoList){ this.mContext=context; this.contactInfoList=contactInfoList; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { MyViewHolder holder = new MyViewHolder( LayoutInflater.from(mContext).inflate( R.layout.contact_item, parent, false)); return holder; } @Override public void onBindViewHolder(MyViewHolder holder, int position) { holder.tv_name.setText(contactInfoList.get(position).getContactName()); holder.tv_phone.setText(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(View view) { super(view); tv_name = view.findViewById(R.id.tv_name); tv_phone = view.findViewById(R.id.tv_phone); iv_photo = view.findViewById(R.id.iv_photo); } } } 7.实现显示界面数据功能

在程序的 java/com.itcast.contacts 包下创建一个 ContactActivity 类, 来申请读取手机通讯录的权限,同时重写 onRequestPermissionsResult () 方法获取通讯录权限是否申请成功。

?代码如下:

package com.itcast.contacts; 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 androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; import java.util.List; public class ContactActivity extends AppCompatActivity { private ContactAdapter adapter; private RecyclerView rv_contact; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_contact); init(); } private void setData(){ List<ContactInfo> contactInfos=getContacts(); adapter=new ContactAdapter(ContactActivity.this,contactInfos); rv_contact.setAdapter(adapter); } public List<ContactInfo> getContacts() { List<ContactInfo> contactInfos = new ArrayList<>(); Cursor cursor = getContentResolver().query(ContactsContract. Contacts.CONTENT_URI, null, null, null, null); if (contactInfos!=null)contactInfos.clear();//清除集合中的数据 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 = Integer.parseInt(cursor.getString(cursor.getColumnIndex( ContactsContract.Contacts.HAS_PHONE_NUMBER))); if (isHas > 0) { Cursor c = getContentResolver().query(ContactsContract. CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id, null, null); while (c.moveToNext()) { ContactInfo info = new ContactInfo(); info.setContactName(name); @SuppressLint("Range") String number = c.getString(c.getColumnIndex(ContactsContract. CommonDataKinds.Phone.NUMBER)).trim(); number = number.replace(" ", ""); number = number.replace("-", ""); info.setPhoneNumber(number); contactInfos.add(info); } c.close(); } } cursor.close(); return contactInfos; } private void init(){ rv_contact=findViewById(R.id.rv_contact); rv_contact.setLayoutManager(new LinearLayoutManager(this)); getPermissions(); } String[] permissionList; public void getPermissions() { if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { permissionList = new String[]{"android.permission.READ_CONTACTS"}; ArrayList<String> list = new ArrayList<String>(); // 循环判断所需权限中有哪个尚未被授权 for (int i = 0; i < permissionList.length; i++) { if (ActivityCompat.checkSelfPermission(this, permissionList[i]) != PackageManager.PERMISSION_GRANTED) list.add(permissionList[i]); } if (list.size() > 0) { ActivityCompat.requestPermissions(this, list.toArray(new String[list.size()]), 1); } else { setData();//后续创建该方法 } } else { setData(); //后续创建该方法 } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, 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(); setData();//后续创建该方法 }else{ Toast.makeText(this,"读取通讯录权限申请失败", Toast.LENGTH_SHORT).show(); } } } } } 8.去掉默认标题栏,添加读取系统通讯录权限

<1> 在 AndroidManifest.xml 文件的 <application> 标签下修改标题栏,使标题栏更加美观。

<2> 因为我们需要使用到系统的通讯录,所以还要在?AndroidManifest.xml 文件中添加读取系统通讯录权限

<3> 同时解决可能会出现虚拟器运行后“ xxx has stopped"的错误,详细内容可以移步到:简单步骤:解决 Android studio 出现 “ xxx(项目名) has stopped ” 的错误_蛇形刁手的博客-CSDN博客

?代码如下:

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="com.itcast.contacts"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.AppCompat.NoActionBar"> <activity android:name=".ContactActivity" android:exported="true" tools:ignore="MissingClass"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-permission android:name="android.permission.READ_CONTACTS" /> </manifest> 9.运行程序

第一次运行时,会弹出一个 “ Allow Contacts to access your contacts?” 窗口,有两个选项: “ ALLOW ” 表示允许读取 和 “ DENY ” 拒绝读取,我们点击允许读取。当第一次运行时,我们的通讯录界面是一片空白,需要我们在系统的通讯录输入联系人信息予以提供。重新切换到我们的通讯录界面后便会出现信息。

图文解释如下:


总结

以上就是 Android studio 内容提供者 - 实现读取手机通讯录的具体操作,由于每个人的配置、编写习惯等等多种原因,如果在实际操作中出现问题,或者发现文章中的错误,也可以在评论区中发表出来,尽能所答,欢迎指点与建议。

如果感到有帮助!!!

编写不易,关注、三连是最大的支持!!!

欢迎建议,感谢支持!!!


1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,会注明原创字样,如未注明都非原创,如有侵权请联系删除!;3.作者投稿可能会经我们编辑修改或补充;4.本站不提供任何储存功能只提供收集或者投稿人的网盘链接。

标签: #Android #studio手机通讯录 #Studio #内容提供者 #实现 #读取手机通讯录 #的项目以列表的形式来显示