LoginSignup
8
8

More than 5 years have passed since last update.

AndroidからOAuth2を使ってGoogle SpreadSheetへアクセスする方法

Last updated at Posted at 2015-02-10

SpreadSheetなどのGoogle Docsへのアクセスの情報は、新旧入り乱れてカオスになってます。
現時点では以下の流れが一番シンプルにできますた。

MainActivity.java
        //※ここにユーザーアカウント選択画面があると素敵だと思います。

        //oauth tokenの取得
        String token;
        try {
            token = GoogleAuthUtil.getToken(this, "shikajiro@gmail.com", "oauth2:https://spreadsheets.google.com/feeds");
            Log.i("TAG", token);
        } catch (UserRecoverableAuthException e) {
            //最初のアクセスの場合かならずここに来る。
            //ユーザーに承認を求める画面が表示される。
            startActivityForResult(e.getIntent(), USER_RECOVERABLE_AUTH);
            return;
        }catch (IOException | GoogleAuthException e) {
            Log.e("TAG", "", e);
            return;
        }

        //Spreadsheetへアクセスするサービス
        SpreadsheetService service = new SpreadsheetService("applicationName");
        service.setProtocolVersion(SpreadsheetService.Versions.V3);
        service.setAuthSubToken(token);//tokenを設定

        //プライベート権限のシート全てにアクセスして、とりあえずタイトル表示する。
        try {
            URL url = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");
            SpreadsheetFeed spreadsheetFeed = service.getFeed(url, SpreadsheetFeed.class);
            Log.i("TAG", spreadsheetFeed.getTitle().getPlainText());
            for (SpreadsheetEntry entry : spreadsheetFeed.getEntries()) {
                Log.i("TAG", entry.getTitle().getPlainText());
            }
        } catch (IOException | ServiceException e) {
            Log.e("TAG", "", e);
        }

    }

    @OnActivityResult(USER_RECOVERABLE_AUTH)
    void onResult(){
        callOauthToken();
    }

AndroidAnnotationを利用して書いています。雰囲気で読んでください。

https://console.developers.google.com/project
で以下みたいなクライアントIDも作っておく必要があるかもしれない。ないかもしれない。
Screen_Shot_2015-02-10_at_19_21_28.png

8
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
8