How to get the number of unread gmail mails (on android)

Solution 1:

Here's some code snippet. Not sure it works and can't test it. But I hope it will help you to continue the investigation.

public static final class LabelColumns {
    public static final String CANONICAL_NAME = "canonicalName";
    public static final String NAME = "name";
    public static final String NUM_CONVERSATIONS = "numConversations";
    public static final String NUM_UNREAD_CONVERSATIONS = "numUnreadConversations";
}

public void queryLabels(){
    String account="[email protected]";
    Uri LABELS_URI = Uri.parse("content://gmail-ls/labels/");
    Uri ACCOUNT_URI = Uri.withAppendedPath(LABELS_URI, account);
    ContentResolver contentResolver=myActivity.getContentResolver();
    Cursor cursor = contentResolver.query(ACCOUNT_URI, null, null, null, null);

    //iterate over all labels in the account
    if (cursor.moveToFirst()) {
        int unreadColumn = cursor.getColumnIndex(LabelColumns.NUM_UNREAD_CONVERSATIONS);
        int nameColumn = cursor.getColumnIndex(LabelColumns.NAME);
        do {
            String name = cursor.getString(nameColumn);
            String unread = cursor.getString(unreadColumn);//here's the value you need
        } while (cursor.moveToNext());
    }
}

Requires permission

<uses-permission android:name="com.google.android.gm.permission.READ_GMAIL"/>

Solution 2:

This is how I've seen it done in a simple widget for the awesome window manager (yes, that's its name :)). Original script is here: gmail.lua.

The basic concept is to just use the inbox feed and get all the mails (you'll get just the summaries, not the whole content) for the special 'unread' tag. The URL is https://mail.google.com/mail/feed/atom/unread, you just have to fetch it (after authentication, of course), and then parse it. You can either use some sort of XML parser or just a simple regexp (<fullcount>([%d]+)</fullcount>) - the number you are looking for is at the beginning, in the <fullcount> tag.

So, that's one way of doing it, quite simple and "dumb", but hey, it works :D It might not be the best solution, as it requires you to fetch the whole feed (depending on the number of your unread messages and the type/quality of connection, it might not be as fast as just fetching the number of unread messages), but as usual, real-life testing should clear that up :)

Solution 3:

There is new way how to do it. Old way doesn´t work anymore (21.01.2013). Check following link: Gmail Public Labels API