适用于 Gmail 的 Android content provider

Android 版 Gmail 应用包含一个 content provider,第三方开发者可以使用该 content provider 检索姓名和未读邮件数等标签信息,并随时了解该信息的变化。例如,应用或微件可以显示特定帐号收件箱的未读邮件计数。

使用此 content provider 之前,请调用 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 */);

查询 content provider

选择电子邮件地址后,您便可以获取用于查询的 ContentProvider URI。我们提供了一个名为 GmailContract.java 的简单类,用于构造 URI 并定义返回的列。

应用可以直接查询此 URI(或者最好使用 CursorLoader)获取一个游标,其中包含帐号中所有标签的信息:

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

有了此游标中的数据后,您可以将 URI 值保留在 GmailContract.Labels.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
        }
    }
}

如需更多帮助,请阅读内容提供程序基础知识

查看示例

如需查看此 content provider 的实际应用示例,请下载示例应用