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
}
}
}
詳情請參閱「內容供應器基礎知識」
查看範例
如要查看此內容供應器的實際應用範例,請下載範例應用程式。