Android 简单通讯录开发

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

添加权限

    
    
    
    
    
    
    
    
    
    

布局
1、主布局 activity_main.xml




    

        

        

    

    

        

2、添加联系人,电话dialog 内部布局contact_add.xml




    

    

    

    

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

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



    通讯录
    添加联系人
    确定
    取消
    添加
    姓名:
    电话:
    打电话
    发短信
    请选择

res\values-ko-rKR\strings.xml



    주소록
    연락처 추가
    확정
    취소
    추가
    이름:
    전화기:
    전화
    문자
    선택하십시오.

res\values-en-rUS\strings.xml



    MailList
    Add a Contact
    OK
    Cancel
    ADD
    Name:
    Phone:
    Phone
    Message
    Please Select

主体代码

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

    private List> 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> getContacts() {
        List> listItems = new ArrayList>();
        Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
        while (cursor.moveToNext()) {
            String phoneName;
            String phoneNumber;
            Map listItem = new HashMap();
            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> 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);
    }


}

你可能感兴趣的:(Android 简单通讯录开发)