已阅读:7,355 次
Android 联系人和消息数据库常用操作
ian | Android | 2012/04/04


本文汇总整理Android系统中,一些常用的联系人和短信数据库常用操作。

1 查询所有会话记录

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
    public static final Map<String,Session> loadSession(ContextWrapper cw)
    {
        Map<String,Session> mapSessionInfo = new HashMap<String,Session>();
        if(cw == null)
            return mapSessionInfo;
 
        String projection = " b.thread_id,b.address from sms b  group by b.address--";
        Cursor cursor1 = cw.getContentResolver().query(
                Uri.parse("content://sms/"),
                new String[] { projection }, null, null, null);
        String address = "";
        int id = 0;
        Map<Integer,String> mapIDToPhone = new HashMap<Integer,String>();
        if (cursor1 != null)
        {
            try
            {
                if (cursor1.moveToFirst())
                {
                    do{
                        id = cursor1.getInt(0);
                        address = cursor1.getString(1);
                        if (address.startsWith("+"))
                        {
                            address = address.substring(3);
                        }
                        mapIDToPhone.put(Integer.valueOf(id), address);
                    } while (cursor1.moveToNext());
 
                }
            }
            catch (Exception e)
            {
                FDebug.e(e.toString());
            }
            finally
            {
                cursor1.close();
            }
        }
 
        String[] ALL_THREADS_PROJECTION = { "_id", "date", "message_count",
                "recipient_ids", "snippet", "snippet_cs", "read", "error",
                "has_attachment" };
        Uri MMSSMS_FULL_CONVERSATION_URI = Uri
                .parse("content://mms-sms/conversations");
        Uri CONVERSATION_URI = MMSSMS_FULL_CONVERSATION_URI.buildUpon()
                .appendQueryParameter("simple", "true").build();
        Cursor cursor = cw.getContentResolver().query(CONVERSATION_URI,
                ALL_THREADS_PROJECTION, null, null, "message_count desc");
        if (cursor != null)
        {
            try
            {
                if (cursor.moveToFirst())
                {
                    do
                    {
                        Session session = new Session();
                        session.mId = (cursor.getInt(Session.ID));
                        session.mTime = cursor.getLong(Session.DATE);
                        session.mMessageCount = (cursor.getInt(Session.MESSAGE_COUNT));
                        session.mRead = (cursor.getInt(Session.READ));
                        session.mRecipiend_ids = (cursor.getString(Session.RECIPIENT_IDS));
                        session.mSnippe = (cursor.getString(Session.SNIPPET));
                        session.mSnippet_cs = (cursor.getLong(Session.SNIPPET_CS));
                        session.mType = (cursor.getInt(Session.TYPE));
 
                        String phone = mapIDToPhone.get(Integer.valueOf(session.mId));
                        if (phone != "" && mapSessionInfo.containsKey(phone) == false)
                            mapSessionInfo.put(phone, session);
                    } while (cursor.moveToNext());
                }
            }
            catch (Exception e)
            {
                FDebug.e(e.toString());
            }
            finally
            {
                cursor.close();
            }
        }
 
        return mapSessionInfo;
    }

2 查询一条通话记录

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
    public static final List<CallLogMessage> queryCallLogs(ContextWrapper cw)
    {
        List<CallLogMessage> calllogList = new ArrayList<CallLogMessage>();
        if (cw == null)
            return calllogList;
 
        String number = "";
        String name = "";
        int id = -1;
        int type = -1;
        long callTime = 0;
        long duration = 0;
        String[] projection = new String[] { CallLog.Calls._ID,
                CallLog.Calls.NUMBER, CallLog.Calls.CACHED_NAME,
                CallLog.Calls.TYPE, CallLog.Calls.DURATION, CallLog.Calls.DATE };
        Cursor cursor = cw.getContentResolver().query(
                CallLog.Calls.CONTENT_URI, projection, null, null,
                CallLog.Calls.DEFAULT_SORT_ORDER);
 
        if (cursor != null)
        {
            try
            {
                if (cursor.moveToFirst())
                {
                    do
                    {
                        id = cursor.getInt(0);
                        number = cursor.getString(1);
                        name = cursor.getString(2);
                        type = cursor.getInt(3);
                        duration = cursor.getLong(4);
                        callTime = cursor.getLong(5);
 
                        CallLogMessage calllog = new CallLogMessage();
                        calllog.setID(id);
                        calllog.setPhoneNumber(number);
                        calllog.setName(name);
                        calllog.setContentType(type);
                        calllog.setDuration(duration);
                        calllog.setTimeline(callTime);
                        calllogList.add(calllog);
 
                    } while (cursor.moveToNext());
                }
            }
            catch (Exception e)
            {
                FDebug.e(e.toString());
            }
            finally
            {
                cursor.close();
                projection = null;
            }
        }
 
        return calllogList;
    }

3 查询某一会话下的所有短信SMS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
    public static final List<UnifiedMessage> querySMSsFromDB(ContextWrapper cw,int threadId)
    {
        List<UnifiedMessage> listSMS = new ArrayList<UnifiedMessage>();
        if(null == cw || threadId < 0)
            return listSMS;
 
        final String SMS_URI_ALL   = "content://sms";
        String[] projection = new String[] { "_id", "address", "body", "date", "type" };  
        Uri uri = Uri.parse(SMS_URI_ALL);  
        Cursor cursor = cw.getContentResolver().query(uri, projection, "thread_id=?",  
                new String[] { Integer.toString(threadId) }, "date desc");
 
        if(cursor != null)
        {
            try
            {
                if (cursor.moveToFirst())
                {
                    do
                    {
                        int idColume = cursor.getColumnIndex("_id"); 
                        int phoneNumberColumn = cursor.getColumnIndex("address");
                        int smsBodyColumn = cursor.getColumnIndex("body");  
                        int dateColumn = cursor.getColumnIndex("date");  
                        int typeColumn = cursor.getColumnIndex("type");
 
                        SMSMessage smsMessage = new SMSMessage();
                        smsMessage.setID(cursor.getInt(idColume));
                        smsMessage.setPhoneNumber(cursor.getString(phoneNumberColumn));
                        smsMessage.setContent(cursor.getString(smsBodyColumn));
                        smsMessage.setTimeline(Long.parseLong(cursor.getString(dateColumn)));
                        smsMessage.setCategory(cursor.getInt(typeColumn));
                        listSMS.add(smsMessage);
 
                    } while (cursor.moveToNext());
                }
            }
            catch (Exception e)
            {
                FDebug.e(e.toString());
            }
            finally
            {
                cursor.close();
                projection = null;
            }
        }
        return listSMS;
    }

4 常用删除操作:删除SMS、MMS、CallLog、Conversion

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
    public static final int deleteSMSFromDB(ContextWrapper cw,int msgId)
    {
        if(cw == null || msgId < 0)
            return 0;
 
        int result = cw.getContentResolver().delete(Uri.parse("content://sms"), "_id=?",
                new String[] { String.valueOf(msgId) });
        return result;
    }
 
    public static final int deleteMMSFromDB(ContextWrapper cw,int msgId)
    {
        if(cw == null || msgId < 0)
            return 0;
 
        int result = cw.getContentResolver().delete(Uri.parse("content://mms"), "_id=?",
                new String[] { String.valueOf(msgId) });
        return result;
    }
 
    public static final int deleteCallLogFromDB(ContextWrapper cw,int calllogId)
    {
        if(cw == null || calllogId < 0)
            return 0;
 
        int result = cw.getContentResolver().delete(CallLog.Calls.CONTENT_URI, "_id=?",
                new String[] { String.valueOf(calllogId) });
        return result;
    }
 
    public static final int deleteConversionFromDB(ContextWrapper cw,int conversionId)
    {
        if(cw == null || conversionId < 0)
            return 0;
 
        Uri uri = Uri.parse("content://sms/conversations/" + conversionId);
 
        int result = cw.getContentResolver().delete(uri, null, null);
        return result;
    }

5 查询所有联系人

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
    public static final List<UnifiedContact> loadContactsFromDB(
            ContextWrapper cw)
    {
        List<UnifiedContact> contactList = new ArrayList<UnifiedContact>();
 
        if (cw == null)
        {
            return contactList;
        }
 
        Map<Long, String> mapPhoneNumbers = new HashMap<Long, String>();
        String[] phoneNumberProjection = new String[] {
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
                ContactsContract.CommonDataKinds.Phone.NUMBER,
                ContactsContract.Contacts.DISPLAY_NAME,
                ContactsContract.Contacts.PHOTO_ID };
 
        Cursor phonecursor = cw.getContentResolver().query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                phoneNumberProjection, null, null, "display_name asc");
        if (phonecursor != null)
        {
            Log.v("FlamingoService", "Contact Count(Has PhoneNumber) :"+phonecursor.getCount());
            try
            {
                while (phonecursor.moveToNext())
                {
                    long contactId = phonecursor.getLong(0);
                    String phoneNumber = phonecursor.getString(1);
                    if (phoneNumber.startsWith("+"))
                    {
                        phoneNumber = phoneNumber.substring(3);
                    }
                    String name = phonecursor.getString(2);
                    long photoid = phonecursor.getLong(3);
 
                    String otherNumber = "";
 
                    if (mapPhoneNumbers.containsKey(contactId))
                    {
                        phoneNumber = phoneNumber + ";"
                                + mapPhoneNumbers.get(contactId);
                        mapPhoneNumbers.put(contactId, phoneNumber);
 
                        phoneNumber = mapPhoneNumbers.get(Long
                                .valueOf(contactId));
                        if (phoneNumber.indexOf(";") > 0)
                        {
                            otherNumber = phoneNumber.substring(
                                    phoneNumber.indexOf(";") + 1,
                                    phoneNumber.length());
                            phoneNumber = phoneNumber.substring(0,
                                    phoneNumber.indexOf(";"));
                        }
                        for (UnifiedContact contact : contactList)
                        {
                            if (contact.getID() == contactId)
                            {
                                ((PhoneContact) contact)
                                        .setPhoneNumber(phoneNumber);
                                ((PhoneContact) contact)
                                        .setOtherPhoneNumber(otherNumber);
                                break;
                            }
                        }
                    }
                    else if (mapPhoneNumbers.containsKey(contactId) == false)
                    {
                        mapPhoneNumbers.put(contactId, phoneNumber);
 
                        PhoneContact contact = new PhoneContact();
                        contact.setID(contactId);
                        contact.setName(name);
                        contact.setPhoneNumber(phoneNumber);
                        contact.setOtherPhoneNumber(otherNumber);
                        contact.setAvatarID(photoid);
                        contactList.add(contact);
                    }
                }
            }
            catch (Exception e)
            {
                FDebug.e(e.toString());
            }
            finally
            {
                phonecursor.close();
                phoneNumberProjection = null;
            }
        }
 
        // 查询电话号码为空的联系人
        String[] projection = new String[] { ContactsContract.Contacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME,
                ContactsContract.Contacts.PHOTO_ID };
        String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + " = "
                + 0;
 
        Cursor cursor = cw.getContentResolver().query(
                ContactsContract.Contacts.CONTENT_URI, projection, selection,
                null, null);
 
        if (cursor != null)
        {
            try
            {
                while (cursor.moveToNext())
                {
                    PhoneContact contact = new PhoneContact();
                    contact.setID(cursor.getLong(0));
                    contact.setName(cursor.getString(1));
                    contact.setAvatarID(cursor.getLong(2));
                    contactList.add(contact);
                }
            }
            catch (Exception e)
            {
                FDebug.e(e.toString());
            }
            finally
            {
                cursor.close();
            }
        }
        return contactList;
    }

代码中有些未列出定义的Class,只需要简单的自定义一下,添加代码中所需的属性即可。

原创文章,转载请注明:转载自ian的个人博客[http://www.icodelogic.com]
本文链接地址: http://www.icodelogic.com/?p=530

tags:

3条评论

  1. Alen 说:

    Android应用的权限这么大么??装一个应用,俺就木有隐私啦?装应用之前的权限警告完全没有人去看的啊。。。。这么说来,似乎又到了360大显身手的时候了

发表评论

你需要先 登录 才能回复