본문 바로가기

Android

[Gmail API] Label Update

폴더명 수정하기

public static void updateMailLabel(Context context, Account account, List<String> mailIds, List<String> addLebelIds, List<String> removeLabelIds, 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 UpdateMailLabelTask(account, service, mailIds, addLebelIds, removeLabelIds, listener).execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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

        private Account account;
        private Gmail service;
        private List<String> mailIds;
        private List<String> addLebelIds;
        private List<String> removeLabelIds;
        private GmailNetworkListener listener;

        public UpdateMailLabelTask(Account account, Gmail service, List<String> mailIds, List<String> addLebelIds, List<String> removeLabelIds, GmailNetworkListener listener) {
            this.account = account;
            this.service = service;
            this.mailIds = mailIds;
            this.addLebelIds = addLebelIds;
            this.removeLabelIds = removeLabelIds;
            this.listener = listener;
        }

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

            try {
                BatchModifyMessagesRequest modifyMessagesRequest = new BatchModifyMessagesRequest().setIds(mailIds).setAddLabelIds(addLebelIds).setRemoveLabelIds(removeLabelIds);
                service.users().messages().batchModify(account.name, modifyMessagesRequest).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);
            }
        }
    }