一、实验目的(如果代码有错漏,可在代码地址查看)
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