提示:本篇文章將會盡量保持精簡,同時請諸位敲寫代碼時保持耐心,三連是最大的支持!
文章目錄
前言
一、項(xiàng)目介紹
二、使用步驟
1.創(chuàng)建程序
2.添加 recyclerview-v7 庫
3.放置界面控件
4.搭建界面布局
5.封裝實(shí)體類
6.編寫數(shù)據(jù)適配器
7.實(shí)現(xiàn)顯示界面數(shù)據(jù)功能
8.去掉默認(rèn)標(biāo)題欄,添加讀取系統(tǒng)通訊錄權(quán)限
9.運(yùn)行程序
總結(jié)
前言
本篇文章將會介紹如何使用?Android studio?內(nèi)容提供者 實(shí)現(xiàn) “讀取手機(jī)通訊錄” 的項(xiàng)目,文章是經(jīng)由本人實(shí)際編寫過后得出,同時項(xiàng)目中的名稱等如有沖突可自行更改。文章盡量保持精簡,也請諸位保持耐心,且會加以圖文解釋,方便讀者能夠更佳觀看。
配置:Android studio 2021.1.1.21 windows??
一、項(xiàng)目介紹
本項(xiàng)目通過顯示一個通訊錄的界面,以列表的形式來顯示 Android 設(shè)備通訊錄中暴露的數(shù)據(jù), 而 Android 便提供了一個組件 ContentProvider(內(nèi)容提供者) 來充當(dāng)一個 “中介” 的角色。具體有關(guān) ContentProvider(內(nèi)容提供者) 的細(xì)節(jié)在這就不再贅述。
二、使用步驟
1.創(chuàng)建程序
打開 Android studio,在 Android studio 創(chuàng)建一個新的應(yīng)用程序,命名為 Contact?,指定包名為 com.itcast.contacts 。
2.添加 recyclerview-v7 庫
因?yàn)槲覀兺ㄓ嶄浗缑鎸⒁褂玫?RecyclerView 控件,以列表的形式展示,所以需要將擁有? RecyclerView 控件的 recyclerview-v7 庫添加進(jìn)程序。但是由于版本和補(bǔ)丁的更新,我們只需要在 Android 的?Gradle Scripts 下的 build.gradle(Module:Contact.app) 中填入一下代碼
代碼如下:
dependencies {
// 。。。。。
implementation 'androidx.recyclerview:recyclerview:1.0.0'
}
更為詳細(xì)的說明可以移步到:簡單步驟:解決 Android studio 2021.1.1 出現(xiàn)添加 “ recyclerview-v7 庫 ”報(bào)錯_蛇形刁手的博客-CSDN博客
3.放置界面控件
在 res/layout 文件夾的 activity_contact.xml 下放置一個 TextView控件 和 RecyclerView 控件來以列表的形式顯示通訊錄和其中聯(lián)系人的信息。?
??代碼如下:
<?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 文件夾下,創(chuàng)建布局文件 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> 導(dǎo)入圖片
將通訊錄界面所需要的圖片 contact_photo.png 導(dǎo)入到 res/drewable?文件夾中。(如果文章會自動生成水印,那么推薦使用自己的圖片)
圖片如下:
<3> 創(chuàng)建條目界面的背景文件
在res/drewable?文件夾中創(chuàng)建 item_bg.xml文件設(shè)置條目背景。
代碼如下:
<?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.封裝實(shí)體類
在程序的 java/com.itcast.contacts 包下創(chuàng)建一個 ContactInfo 類,用來創(chuàng)建聯(lián)系人信息的屬性。
?代碼如下:
package com.itcast.contacts;
public class ContactInfo {
private String contactName; //聯(lián)系人名稱
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.編寫數(shù)據(jù)適配器
在程序的 java/com.itcast.contacts 包下創(chuàng)建一個 ContactAdapter?類,由于我們使用了 RecyclerView 控件,所以就需要創(chuàng)建一個數(shù)據(jù)適配器,來對 RecyclerView 控件進(jìn)行數(shù)據(jù)適配。
?代碼如下:
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.實(shí)現(xiàn)顯示界面數(shù)據(jù)功能
在程序的 java/com.itcast.contacts 包下創(chuàng)建一個 ContactActivity 類, 來申請讀取手機(jī)通訊錄的權(quán)限,同時重寫 onRequestPermissionsResult () 方法獲取通訊錄權(quán)限是否申請成功。
?代碼如下:
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();//清除集合中的數(shù)據(jù)
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>();
// 循環(huán)判斷所需權(quán)限中有哪個尚未被授權(quán)
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();//后續(xù)創(chuàng)建該方法
}
} else {
setData(); //后續(xù)創(chuàng)建該方法
}
}
@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, "讀取通訊錄權(quán)限申請成功",
Toast.LENGTH_SHORT).show();
setData();//后續(xù)創(chuàng)建該方法
}else{
Toast.makeText(this,"讀取通訊錄權(quán)限申請失敗",
Toast.LENGTH_SHORT).show();
}
}
}
}
}
8.去掉默認(rèn)標(biāo)題欄,添加讀取系統(tǒng)通訊錄權(quán)限
<1> 在 AndroidManifest.xml 文件的 <application> 標(biāo)簽下修改標(biāo)題欄,使標(biāo)題欄更加美觀。
<2> 因?yàn)槲覀冃枰褂玫较到y(tǒng)的通訊錄,所以還要在?AndroidManifest.xml 文件中添加讀取系統(tǒng)通訊錄權(quán)限
<3> 同時解決可能會出現(xiàn)虛擬器運(yùn)行后“ xxx has stopped"的錯誤,詳細(xì)內(nèi)容可以移步到:簡單步驟:解決 Android studio 出現(xiàn) “ xxx(項(xiàng)目名) 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.運(yùn)行程序
第一次運(yùn)行時,會彈出一個 “ Allow Contacts to access your contacts?” 窗口,有兩個選項(xiàng): “ ALLOW ” 表示允許讀取 和 “ DENY ” 拒絕讀取,我們點(diǎn)擊允許讀取。當(dāng)?shù)谝淮芜\(yùn)行時,我們的通訊錄界面是一片空白,需要我們在系統(tǒng)的通訊錄輸入聯(lián)系人信息予以提供。重新切換到我們的通訊錄界面后便會出現(xiàn)信息。
圖文解釋如下:
總結(jié)
以上就是 Android studio 內(nèi)容提供者 - 實(shí)現(xiàn)讀取手機(jī)通訊錄的具體操作,由于每個人的配置、編寫習(xí)慣等等多種原因,如果在實(shí)際操作中出現(xiàn)問題,或者發(fā)現(xiàn)文章中的錯誤,也可以在評論區(qū)中發(fā)表出來,盡能所答,歡迎指點(diǎn)與建議。
如果感到有幫助!?。?/strong>
編寫不易,關(guān)注、三連是最大的支持?。?!文章來源:http://www.zghlxwxcb.cn/news/detail-483200.html
歡迎建議,感謝支持?。?!文章來源地址http://www.zghlxwxcb.cn/news/detail-483200.html
到了這里,關(guān)于簡單步驟:Android studio 內(nèi)容提供者 - 實(shí)現(xiàn)建立手機(jī)通訊錄界面,讀取系統(tǒng)聯(lián)系人的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!