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

前端 未结 5 623
忘掉有多难
忘掉有多难 2020-11-27 02:31

Please note there is a new way of doing this

I\'ve been trying to get the number of unread gmail mails with no luck.

I\'ve read Gmail.java and gmail4j both l

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 03:20

    static final String AUTHORITY = "com.google.android.gm";
    static final String BASE_URI_STRING = "content://" + AUTHORITY;
    static final String LABELS_PARAM = "/labels";
    static final String ACCOUNT_TYPE_GOOGLE = "com.google";
    
    public static final String NUM_UNREAD_CONVERSATIONS = "numUnreadConversations";
    public static final String CANONICAL_NAME = "canonicalName";
    
    public static final String CANONICAL_NAME_INBOX_CATEGORY_PRIMARY = "^sq_ig_i_personal";
    static String[] GMAIL_PROJECTION = {
        CANONICAL_NAME, NUM_UNREAD_CONVERSATIONS
        };
    
    public static Uri getLabelsUri(String account) {
        return Uri.parse(BASE_URI_STRING + "/" + account + LABELS_PARAM);
    }
    
    static String[] getAllAccountNames(Context context) {
       final Account[] accounts = AccountManager.get(context).getAccountsByType(
               ACCOUNT_TYPE_GOOGLE);
       final String[] accountNames = new String[accounts.length];
       for (int i = 0; i < accounts.length; i++) {
           accountNames[i] = accounts[i].name;
       }
       return accountNames;
    }
    
    
    protected static int getGmail(Context context) {
        ContentResolver cr = context.getContentResolver();
        Cursor cursor =        cr.query(Launcher.getLabelsUri(BadgeUtils.getAllAccountNames(context)[0]),
                GMAIL_PROJECTION,
                null, null,
                null);
    
        if (cursor == null || cursor.isAfterLast()) {
            Log.d(TAG, "No Gmail inbox information found for account.");
            if (cursor != null) {
                cursor.close();
            }
            return 0;
        }
    
        int count = 0;
    
        while (cursor.moveToNext()) {
            if (CANONICAL_NAME_INBOX_CATEGORY_PRIMARY.equals(cursor.getString(cursor.getColumnIndex(CANONICAL_NAME)))) {
                count = cursor.getInt(cursor.getColumnIndex(NUM_UNREAD_CONVERSATIONS));;
                break;
            }
        }
    
        cursor.close();
    
    
        return count;
    }
    

    Hope above code helps. This should work on Android 2.2+.

提交回复
热议问题