Gmail 的 Android 內容供應器

Android 版 Gmail 應用程式包含內容供應器,第三方開發人員可使用該供應器擷取標籤資訊 (例如名稱和未讀郵件數),並在資訊變更時保持最新狀態。舉例來說,應用程式或小工具可以顯示特定帳戶收件匣的未讀郵件數量。

使用這個內容供應器前,請先呼叫 GmailContract.canReadLabels(Context) 方法,判斷使用者的 Gmail 應用程式版本是否支援這些查詢。

尋找要查詢的有效 Gmail 帳戶

應用程式必須先找出有效 Gmail 帳戶的電子郵件地址,才能查詢標籤資訊。有了 GET_ACCOUNTS 權限,AccountManager 就能傳回下列資訊:

// Get the account list, and pick the first one
final String ACCOUNT_TYPE_GOOGLE = "com.google";
final String[] FEATURES_MAIL = {
        "service_mail"
};
AccountManager.get(this).getAccountsByTypeAndFeatures(ACCOUNT_TYPE_GOOGLE, FEATURES_MAIL,
        new AccountManagerCallback() {
            @Override
            public void run(AccountManagerFuture future) {
                Account[] accounts = null;
                try {
                    accounts = future.getResult();
                    if (accounts != null && accounts.length > 0) {
                        String selectedAccount = accounts[0].name;
                        queryLabels(selectedAccount);
                    }

                } catch (OperationCanceledException oce) {
                    // TODO: handle exception
                } catch (IOException ioe) {
                    // TODO: handle exception
                } catch (AuthenticatorException ae) {
                    // TODO: handle exception
                }
            }
        }, null /* handler */);

查詢內容供應器

選取電子郵件地址後,即可取得要查詢的 URI。ContentProvider我們提供名為 GmailContract.java 的簡單類別,用於建構 URI 和定義傳回的資料欄。

應用程式可以直接查詢這個 URI,或使用 CursorLoader 取得含有帳戶中所有標籤資訊的 Cursor:

Cursor labelsCursor = getContentResolver().query(GmailContract.Labels.getLabelsUri(selectedAccount), null, null, null, null);

有了這個游標中的資料,您就可以在 GmailContract.Labels.URI 欄中保留 URI 值,以便查詢及監控單一標籤的變更。

預先定義標籤的 NAME 值可能因語言代碼而異,因此請勿使用 GmailContract.Labels.NAME。不過,您可以使用「GmailContract.Labels.CANONICAL_NAME」欄中的字串值,以程式輔助方式識別預先定義的標籤,例如「收件匣」、「寄件備份」或「草稿」:

// loop through the cursor and find the Inbox
if (labelsCursor != null) {
    final String inboxCanonicalName = GmailContract.Labels.LabelCanonicalName.CANONICAL_NAME_INBOX;
    final int canonicalNameIndex = labelsCursor.getColumnIndexOrThrow(GmailContract.Labels.CANONICAL_NAME);
    while (labelsCursor.moveToNext()) {
        if (inboxCanonicalName.equals(labelsCursor.getString(canonicalNameIndex))) {
            // this row corresponds to the Inbox
        }
    }
}

如需更多說明,請參閱「內容供應器基礎知識

查看範例

如要查看這個內容供應器運作的範例,請下載範例應用程式