Search code examples
androidsmsmanager

Way to know number of unread message from a particular number


I am getting number of unread message in inbox by the following code .

public int getMessageCountUnread(){
        resolver = getContentResolver() ; 
        Cursor c = resolver.query(SMS_INBOX, null, "read = 0", null, null);
        int unreadMessagesCount = c.getCount();
        c.deactivate();
        return unreadMessagesCount;
    }

Now I want to know the number of unread sms from a particular number. How can I know the number of unread SMS from a particular number?

How can I set the query ?
WHAT to do if I want to know no of read messages from a particular number ?


Solution

  • Use columns from android.provider.Telephony.TextBasedSmsColumns in your ContentResolver query to find SMS messages that are from a specific address and not read:

    Use these column contants:

    Telephony.TextBasedSmsColumns.ADDRESS
    Telephony.TextBasedSmsColumns.READ
    

    Something like this:

    ContentResolver resolver = context.getContentResolver();
    Cursor cursor = resolver.query(Telephony.Sms.CONTENT_URI,
                    null,
                    Telephony.TextBasedSmsColumns.READ + " = ? and "
                    + Telephony.TextBaseSmsColumns.ADDRESS + "= ?"   ,
                    new String[]{"false", "+1 123 123 1234"},
                    Telephony.Sms.Conversations.DEFAULT_SORT_ORDER);
    int unreadCount = cursor.getCount();
    

    And to know no of read messages from a particular number, just a minor change:

    Cursor cursor = resolver.query(Telephony.Sms.CONTENT_URI,
                        null,
                        Telephony.TextBasedSmsColumns.READ + " = ? and "
                        + Telephony.TextBaseSmsColumns.ADDRESS + "= ?"   ,
                        new String[]{"true", "+1 123 123 1234"},
                        Telephony.Sms.Conversations.DEFAULT_SORT_ORDER);
    

    Update:

    If above code doesn't work, use this:

    String address = 0123456789;
    Cursor unreadcountcursor = getContentResolver().query(Uri.parse("content://sms/inbox"), 
    new String[]{}, "read = 0 and address='"+address+"'", null, null); 
    int count = unreadcountcursor.getCount();