Android 简单通讯录开发

1、可以添加联系人
2、可以发短信,打电话

添加权限

    <!-- 读取通讯录权限 -->
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <!-- 写入通讯录权限 -->
    <uses-permission android:name="android.permission.WRITE_CONTACTS" />
    <!-- 拨号权限 -->
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <!-- 读短信权限 -->
    <uses-permission android:name="android.permission.READ_SMS" />
    <!--发送短信权限-->
    <uses-permission android:name="android.permission.SEND_SMS"/>

布局
1、主布局 activity_main.xml

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical">

        <ListView
            android:id="@+id/lvPhones"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        </ListView>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="bottom"
        android:orientation="vertical">

        <Button
            android:id="@+id/btnAdd"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/btnAdd" />
    </LinearLayout>
</LinearLayout>

2、添加联系人,电话dialog 内部布局contact_add.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="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/tvName" />

    <EditText
        android:id="@+id/edtName"
        android:inputType="textPhonetic"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/tvPhone" />

    <EditText
        android:id="@+id/edtPhone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="phone"
        android:text="" />
</LinearLayout>

主要代码
1、没有对方法进行封装,全写在Activity中了,最好把逻辑方法封装到一个类中,进行调用

另外做了简单适配,支持中文简体、韩文、英文
res\values-zh-rCN\strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">通讯录</string>
    <string name="addContact">添加联系人</string>
    <string name="btnOK">确定</string>
    <string name="btnCancel">取消</string>
    <string name="btnAdd">添加</string>
    <string name="tvName">姓名:</string>
    <string name="tvPhone">电话:</string>
    <string name="callPhone">打电话</string>
    <string name="sendMessage">发短信</string>
    <string name="qxz">请选择</string>
</resources>

res\values-ko-rKR\strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">주소록</string>
    <string name="addContact">연락처 추가</string>
    <string name="btnOK">확정</string>
    <string name="btnCancel">취소</string>
    <string name="btnAdd">추가</string>
    <string name="tvName">이름:</string>
    <string name="tvPhone">전화기:</string>
    <string name="callPhone">전화</string>
    <string name="sendMessage">문자</string>
    <string name="qxz">선택하십시오.</string>
</resources>

res\values-en-rUS\strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">MailList</string>
    <string name="addContact">Add a Contact</string>
    <string name="btnOK">OK</string>
    <string name="btnCancel">Cancel</string>
    <string name="btnAdd">ADD</string>
    <string name="tvName">Name:</string>
    <string name="tvPhone">Phone:</string>
    <string name="callPhone">Phone</string>
    <string name="sendMessage">Message</string>
    <string name="qxz">Please Select</string>
</resources>

主体代码

public class MainActivity extends AppCompatActivity {
    private Button btnAdd;
    private ListView lvPhones;
    private TextView tvPhoneName;
    private TextView tvPhoneNumber;
    private EditText edtPhone;

    private List<Map<String, Object>> ContactsList;  //存储所有通讯录信息

    //获取系统自定义字符串
    @Override
    public Resources getResources() {
        return super.getResources();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnAdd = (Button) findViewById(R.id.btnAdd);      //添加
        lvPhones = (ListView) findViewById(R.id.lvPhones);//显示

        //显示联系人
        InitData();

        //添加联系人
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle(getResources().getString(R.string.addContact));
                //    通过LayoutInflater来加载一个xml的布局文件作为一个View对象
                View view1 = LayoutInflater.from(MainActivity.this).inflate(R.layout.contact_add, null);

                builder.setView(view1);

                final EditText edtName = (EditText) view1.findViewById(R.id.edtName);
                final EditText edtPhone = (EditText) view1.findViewById(R.id.edtPhone);

                //确定操作
                builder.setPositiveButton(getResources().getString(R.string.btnOK), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String strName = edtName.getText().toString().trim();
                        String strPhone = edtPhone.getText().toString().trim();
                        if (strPhone.isEmpty()) {
                            Toast.makeText(getApplicationContext(), "电话号码为空,添加失败!", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        String telRegex = "((\\d{11})|^((\\d{7,8})|(\\d{4}|\\d{3})-(\\d{7,8})|(\\d{4}|\\d{3})-(\\d{7,8})-(\\d{4}|\\d{3}|\\d{2}|\\d{1})|(\\d{7,8})-(\\d{4}|\\d{3}|\\d{2}|\\d{1}))$)";  //
                        if (!edtPhone.getText().toString().matches(telRegex)) {
                            Toast.makeText(getApplicationContext(), "请重新输入正确的电话号码,添加失败!", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        writeContacts(strName, strPhone);    //添加联系人
                        InitData();
                    }
                });

                //取消操作
                builder.setNegativeButton(getResources().getString(R.string.btnCancel), null);

                builder.show();

            }
        });

        //为ListView的列表项选中事件绑定事件监听器
        lvPhones.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //取得电话号码
                final String phoneNumber = ContactsList.get(i).get("phoneNumber").toString();

                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle(getResources().getString(R.string.qxz));
                final String[] contactFun = new String[]{getResources().getString(R.string.callPhone), getResources().getString(R.string.sendMessage)};
                builder.setItems(contactFun, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String strFun = contactFun[i];
                        if (strFun.equals(getResources().getString(R.string.callPhone))) {
                            Intent phoneIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNumber));
                            startActivity(phoneIntent);
                        } else {
                            Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + phoneNumber + ""));
                            intent.putExtra("sms_body", "");
                            startActivity(intent);
                        }
                    }
                });
                //取消操作
                builder.setNegativeButton(getResources().getString(R.string.btnCancel), null);
                builder.show();
            }
        });

    }


    //写入通讯录
    public void writeContacts(String strName, String strPhone) {
        ContentResolver resolver = getContentResolver();
        Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
        Uri dataUri = Uri.parse("content://com.android.contacts/data");

        //查出最后一个ID
        Cursor cursor = resolver.query(uri, new String[]{"_id"}, null, null, null);
        cursor.moveToLast();
        int lastId = cursor.getInt(0);
        int newId = lastId + 1;

        //插入一个联系人id
        ContentValues values = new ContentValues();
        values.put("contact_id", newId);
        resolver.insert(uri, values);

        //插入电话数据
        values.clear();
        values.put("raw_contact_id", newId);
        values.put("mimetype", Phone.CONTENT_ITEM_TYPE);
        values.put(Phone.NUMBER, strPhone);
        resolver.insert(dataUri, values);

        //插入姓名数据
        values.clear();
        values.put("raw_contact_id", newId);
        values.put("mimetype", StructuredName.CONTENT_ITEM_TYPE);
        values.put(StructuredName.DISPLAY_NAME, strName);
        resolver.insert(dataUri, values);
    }

    //获取通讯录
    public List<Map<String, Object>> getContacts() {
        List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
        Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
        while (cursor.moveToNext()) {
            String phoneName;
            String phoneNumber;
            Map<String, Object> listItem = new HashMap<String, Object>();
            phoneName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            listItem.put("phoneName", phoneName);
            listItem.put("phoneNumber", phoneNumber);
            listItems.add(listItem);
        }
        return listItems;
    }

    //初始化ListView数据
    public void InitData() {
        List<Map<String, Object>> contacts = getContacts();  //获取通讯录
        ContactsList = contacts;
        SimpleAdapter adapterPhones = new SimpleAdapter(this, contacts,
                R.layout.simple_item,
                new String[]{"phoneName", "phoneNumber"},
                new int[]{R.id.tvPhoneName, R.id.tvPhoneNumber});

        ListView lvPhones = (ListView) findViewById(R.id.lvPhones);
        lvPhones.setAdapter(adapterPhones);
    }


}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容