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 */);
查詢內容供應器
選取電子郵件地址後,您可以取得 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
}
}
}
詳情請參閱「內容供應器基本概念」一文
查看範例
如要查看內容供應器的實際操作範例,請下載範例應用程式。