본문 바로가기

Android

[Gmail API] Create Label

Create Gmail Label in Android 

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

    private static class CreateLabelTask extends AsyncTask<Void, Void, Label> {

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

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

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

            try {
                Label newLabel = new Label().setName(labelName).setLabelListVisibility("labelShow").setMessageListVisibility("hide");
                return service.users().labels().create(account.name, newLabel).execute();
            } catch (IOException e) {
                e.printStackTrace();
                listener.onFailure(e.toString());
            }
            return null;
        }

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