如何在android中删除sim中的联系人

时间:2014-08-12 06:35:04

标签: android android-contacts android-cursor

我做了以下代码,用于从SIM卡中删除选定的联系人。但它不会删除,也不会丢失任何错误。

protected void DeleteContacts(ArrayList<String> ids){

        int flg = 0;

        String[] strids = new String[ids.size()];
        strids = ids.toArray(strids);

        for (int i = 0; i < strids.length; i++) {

            Cursor sims = getActivity().getContentResolver().query(
                    Uri.parse("content://icc/adn"), null,
                    "_id=?", new String[]{strids[i]}, null);

            sims.moveToFirst();
            if (sims.getCount()>0) {
                String phoneNumber = sims.getString(sims.getColumnIndex("number"));
                boolean val = deleteContact(phoneNumber);
                if (!val)
                    flg=1;
            }

            if (flg == 0)
                Toast.makeText(getActivity(), "Contact Deleted", Toast.LENGTH_SHORT).show();
            sims.close();
        }
    }

    public boolean deleteContact(String phone) {
        Cursor cur = getActivity().getContentResolver().query(Uri.parse("content://icc/adn"), null, "number=?", new String[] { phone }, null);
        try {
            if (cur.moveToFirst()) {
                do {
                    String lookupKey = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
                    Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
                    getActivity().getContentResolver().delete(uri, null, null);
                    return true;
                } while (cur.moveToNext());
            }
        } catch (Exception e) {
            System.out.println(e.getStackTrace());
        }
        return false;
    }

2 个答案:

答案 0 :(得分:1)

您正在从sqlite数据库而不是SIM卡中删除联系人。要从SIM卡中删除联系人,您只需要删除Uri.parse(“content:// icc / adn”)uri。但是要删除,您需要提供姓名和号码。名称列必须指定为标记。在此处检查删除方法https://android.googlesource.com/platform/frameworks/opt/telephony/+/9ebea45a36838f0547a9c30f7cd9c60b03aab3b4/src/java/com/android/internal/telephony/IccProvider.java

答案 1 :(得分:1)

基于my answer here,以下是解决方案:

Uri simUri = Uri.parse("content://icc/adn/");
ContentResolver mContentResolver = this.getContentResolver();
Cursor c = mContentResolver.query(simUri, null, null, null, null);
if (c.moveToFirst())
{
    do
    {
        if (/* your condition here */)
        {
            mContentResolver.delete(
                simUri,
                "tag='" + c.getString(c.getColumnIndex("name")) +
                "' AND " +
                "number='" + c.getString(c.getColumnIndex("number")) + "'"
                , null);
            break;
        }                       
    }
    while (c.moveToNext());
}

当然,不要忘记这些权限:

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