Android Gmail 应用包含内容提供程序,第三方开发者可以使用它来检索标签和未读邮件等标签信息,并在此信息发生更改时随时更新。例如,某个应用或微件可以显示特定帐号的收件箱的未读邮件数。
在使用 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);
有了此游标中的数据,您就可以保留 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
}
}
}
如需更多帮助,请参阅内容提供程序基础知识
查看示例
如需查看此 Content Provider 的实际应用示例,请下载示例应用。