본문 바로가기

Android

[Gmail API] Delete Label

Delete Gmail Label in Android

 public static void deleteLabel(Context context, Account account, String labelId, 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 DeleteLabelTask(account, service, labelId, listener).execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class DeleteLabelTask extends AsyncTask<Void, Void, Boolean> {

        private Account account;
        private Gmail service;
        private String labelId;
        private GmailNetworkListener listener;

        public DeleteLabelTask(Account account, Gmail service, String labelId, GmailNetworkListener listener) {
            this.account = account;
            this.service = service;
            this.labelId = labelId;
            this.listener = listener;
        }

        @Override
        protected Boolean doInBackground(Void... voids) {
            if (listener == null) return Boolean.FALSE;

            try {
                service.users().labels().delete(account.name, labelId).execute();
                return Boolean.TRUE;
            } catch (IOException e) {
                e.printStackTrace();
                listener.onFailure(e.toString());
            }
            return Boolean.FALSE;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            if (listener != null) {
                listener.onSuccess(result);
            }
        }
    }