编程实现ContentResolver对系统中所有联系人的访问

文章目录

  • 一、思路:
  • 二、结果:
  • 三、代码:
    • 1、布局文件
    • 2、程序文件
    • 3、配置文件
    • over

此文章可用于熟悉ContentResolver使用场景,同样是适用于为实验苦恼你

设计App通过ContentResolver的使用场景,访问系统中所有联系人并将其以列表形式展示出来,长按联系人姓名会弹出菜单显示添加、删除、排号等相关操作,选择菜单执行相关操作,如选择删除将删除选中的联系人,选择拔号将拔打该号码。

一、思路:

在MainActivity的init()方法中,程序根据geContentResolver()获取系统的联系人id、姓名和电话号码,设置到listView中列表展示。同时通过setOnCreateContextMtenuL.item()方法为listView 关联上下文菜单,当在listviewitem上长按时,会弹出上下文菜单。单击“添加”按钮,会弹出Toast提示当前选择的联系人姓名。单击“删除”按钮,会根据id删除联系人的电话号码,同时删除联系人的姓名信息。单击“拨号”按钮时,会通过Intent调用Item.ACTION CALL的系统action,从而实现给号功能。

二、结果:

编程实现ContentResolver对系统中所有联系人的访问_第1张图片
编程实现ContentResolver对系统中所有联系人的访问_第2张图片

三、代码:

1、布局文件

设置listview并显示联系人姓名:

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

    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="5dp"
        android:divider="#d9d9d9"
        android:dividerHeight="1dp" />

</LinearLayout>

设置姓名在item中显示的样式:

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

    <TextView
        android:id="@+id/txt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:textColor="#0F0F00"/>
</LinearLayout>

2、程序文件

MainActivity.java

package com.example.myexperiment4243;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

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

public class MainActivity extends AppCompatActivity {

    private ListViewAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_1);
        mAdapter = new ListViewAdapter(this);
        init();
        ListView listView = findViewById(R.id.lv);
        listView.setAdapter(mAdapter);
        listView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                menu.setHeaderTitle("选择操作");
                menu.add(0, 0, 0, "添加");
                menu.add(0, 1, 0, "删除");
                menu.add(0, 2, 0, "拨号");
            }
        });

    }

    private void init() {
        List<Contact> contact = new ArrayList<>();
        Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        while (cursor.moveToNext()) {
            String id = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
            String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            Cursor c = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone._ID + "=" + id, null, null);
            List<String> phones = new ArrayList<String>();
            while (c.moveToNext()) {
                String phone = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                phones.add(phone);
            }
            contact.add(new Contact(id, name, phones));

        }
        mAdapter.updateContact(contact);
    }

    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        int postion = menuInfo.position;
        Contact contact = (Contact) mAdapter.getItem(postion);
        switch (item.getItemId()) {
            case 0:
                Toast.makeText(this, "add:" + contact.getName(), Toast.LENGTH_SHORT).show();
                return true;
            case 1:
                deleteContact(contact);
                return true;
            case 2:
                Intent intent = new Intent(Intent.ACTION_CALL);
                Uri data = Uri.parse("tel:" + contact.getPhone().get(0));
                intent.setData(data);
                startActivity(intent);
                return true;
            default:
                return super.onContextItemSelected(item);


        }
    }
    private void deleteContact(Contact contact){
        ContentResolver Resolver = getContentResolver();
        Resolver.delete(ContactsContract.Contacts.CONTENT_URI,ContactsContract.Contacts._ID+"=?",new String[]{String.valueOf(contact.getId())});
        Resolver.delete(ContactsContract.RawContacts.CONTENT_URI,ContactsContract.RawContacts.CONTACT_ID+"=?",new String[]{String.valueOf(contact.getId())});
        Resolver.delete(ContactsContract.RawContacts.CONTENT_URI,"display_name=?",new String[]{String.valueOf(contact.getName())});

    }
}

ListViewAdapter.java

package com.example.myexperiment4243;

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

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

public class ListViewAdapter extends BaseAdapter {

    private LayoutInflater inflater;
    private List<Contact> mDatas;


    public ListViewAdapter(Context context){
        inflater = LayoutInflater.from(context);
        mDatas = new ArrayList<Contact>();
    }
    public void updateContact(List<Contact> files){
        mDatas.clear();
        mDatas.addAll(files);
    }
    @Override
    public int getCount() {
        return (null==mDatas||mDatas.isEmpty())?0:mDatas.size();
    }

    @Override
    public Object getItem(int position) {
        if(mDatas!=null&&position<mDatas.size()){
            return mDatas.get(position);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(null==convertView){
            convertView = inflater.inflate(R.layout.act_2,null);
        }
        TextView textView = convertView.findViewById(R.id.txt);
        Contact contact = (Contact) getItem(position);
        if(null!=contact){
            textView.setText(contact.getName());
        }



        return convertView;
    }
}

Contact.java

package com.example.myexperiment4243;


import java.util.List;

class Contact {
    private String id;
    private String name;
    private  List<String> phone;

    public Contact(String id, String name, List<String> phones) {
        this.id = id;
        this.name = name;
        this.phone = phones;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public List<String> getPhone() {
        return phone;
    }

    public void setPhone(List<String> phone) {
        this.phone = phone;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }
}

3、配置文件

添加代码:

<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
<uses-permission android:name="android.permission.CALL_PHONE"/>

over

在这里插入图片描述

你可能感兴趣的:(Android)