Load unread Gmail Count in Android
public static void loadUnreadCount(Context context, Account account, GmailNetworkListener listener) {
try {
GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(context, Collections.singleton(MAIL_SCOPE));
credential.setSelectedAccount(account);
Gmail service = new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).build();
new GetUnreadCount(account, service, listener).execute();
} catch (Exception e) {
e.printStackTrace();
}
}
private static class GetUnreadCount extends AsyncTask<Void, Void, List<Label>> {
private Account account;
private Gmail service;
private GmailNetworkListener listener;
private List<Label> labelList;
public GetUnreadCount(Account account, Gmail service, GmailNetworkListener listener) {
this.account = account;
this.service = service;
this.listener = listener;
this.labelList = new ArrayList<>();
}
final JsonBatchCallback<Label> callback = new JsonBatchCallback<Label>() {
@Override
public void onSuccess(Label label, HttpHeaders responseHeaders) throws IOException {
labelList.add(label);
}
@Override
public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) throws IOException {
}
};
@Override
protected List<Label> doInBackground(Void... voids) {
if (listener == null) return null;
try {
ListLabelsResponse response = service.users().labels().list(account.name).execute();
BatchRequest batch = service.batch();
for (Label item : response.getLabels()) {
service.users().labels().get(account.name, item.getId()).queue(batch, callback);
}
batch.execute();
return labelList;
} catch (IOException e) {
e.printStackTrace();
listener.onFailure(e.toString());
}
return null;
}
@Override
protected void onPostExecute(List<Label> result) {
super.onPostExecute(result);
if (listener != null) {
listener.onSuccess(result);
}
}
}