7

私は、Google カレンダー API と通信する必要がある Android Honeycomb (v3.0) アプリケーションに取り組んでいます。イベントの読み取りと作成のために、アプリケーションが特定の Google アカウントのカレンダー データにアクセスできるようにしたいと考えています。

残念ながら、OAuth2 を使用した認証で問題が発生しました。これが私がこれまでに持っているものです:

1) アクセスしたいカレンダーの Google アカウントが、使用している Android デバイスに登録されている。

2) アカウントの Google API コンソールで Calendar API を有効にしました。

3) 次のコードを使用して、このアカウントにアクセスできます。

AccountManager accountManager = AccountManager.get(this.getBaseContext());
Account[] accounts = accountManager.getAccountsByType("com.google");
Account acc = accounts[0]; // The device only has one account on it

4) カレンダーと通信するときに使用する AuthToken を取得したいと考えています。このチュートリアルに従いましたが、Google タスクではなく Google カレンダーで動作するようにすべてを変換しました。withを使用して、使用したいアカウントでauthTokenからを正常に取得しました。AccountManagergetAuthTokenAUTH_TOKEN_TYPE == "oauth2:https://www.googleapis.com/auth/calendar"

5) ここから問題が始まります。私は今この時点にいます:

AccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(tokens[0]); // this is the correct token
HttpTransport transport = AndroidHttp.newCompatibleTransport();
Calendar service = Calendar.builder(transport, new JacksonFactory())
    .setApplicationName("My Application's Name")
    .setHttpRequestInitializer(accessProtectedResource)
    .build();
service.setKey("myCalendarSimpleAPIAccessKey"); // This is deprecated???
Events events = service.events().list("primary").execute(); // Causes an exception!

6) 最後の行で返される例外は次のとおりです。

com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
  "code" : 403,
  "errors" : [ {
    "domain" : "usageLimits",
    "message" : "Daily Limit Exceeded. Please sign up",
    "reason" : "dailyLimitExceededUnreg",
    "extendedHelp" : "https://code.google.com/apis/console"
  } ],
  "message" : "Daily Limit Exceeded. Please sign up"
}

7) このGoogle API ビデオ(該当するコンテンツに到達するまで 1 分ほど待ちます) によると、この例外の理由は、アカウントの Google API コンソール内で API アクセスを有効にしていないことが原因である可能性があります。しかし、2) を見ると、私がそうしたことがわかります。

Calendar.setKey8)メソッドが廃止されたため、Simple API Access Key を正しく設定できなかったことが問題のようです。以前にリンクした Google Tasks チュートリアル内で、キーは を使用して設定されTasks.accessKey = "key"ます。ただし、Calendar API でこれを機能させる方法はわかりません。複数の Google アカウントを試しましたが、いずれも 5 の例外が発生しました)。

9) OAuth2 を使用する従来の方法がうまく機能したことを指摘したいと思います。そのために使用したコードは次のとおりです。

HttpTransport TRANSPORT = new NetHttpTransport();
JsonFactory JSON_FACTORY = new JacksonFactory();
String SCOPE = "https://www.googleapis.com/auth/calendar";
String CALLBACK_URL = "urn:ietf:wg:oauth:2.0:oob";
String CLIENT_ID = "myClientID";
String CLIENT_SECRET = "myClientSecret";
String authorizeUrl = new GoogleAuthorizationRequestUrl(CLIENT_ID, CALLBACK_URL, SCOPE).build();
String authorizationCode = "???"; // At this point, I have to manually go to the authorizeUrl and grab the authorization code from there to paste it in here while in debug mode

GoogleAuthorizationCodeGrant authRequest = new GoogleAuthorizationCodeGrant(TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET, authorizationCode, CALLBACK_URL);
authRequest.useBasicAuthorization = false;
AccessTokenResponse authResponse = authRequest.execute();
String accessToken = authResponse.accessToken; // gets the correct token

GoogleAccessProtectedResource access = new GoogleAccessProtectedResource(accessToken, TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET, authResponse.refreshToken);
HttpRequestFactory rf = TRANSPORT.createRequestFactory(access);
AccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(accessToken);
HttpTransport transport = AndroidHttp.newCompatibleTransport();

Calendar service = Calendar.builder(transport, new JacksonFactory())
    .setApplicationName("My Application's Name")
    .setHttpRequestInitializer(accessProtectedResource)
    .build();

Events events = service.events().list("primary").execute(); // this works!

10) 最後に、私の質問: Google カレンダー API で使用する OAuth2 トークンを取得するために、デバイス自体の AccountManager からアカウントを使用したいと考えています。2 番目の方法は、ユーザーが手動で Web ブラウザーにアクセスして認証コードを取得する必要があり、ユーザー フレンドリーではないため、私には役に立ちません。誰にもアイデアはありますか?長文失礼しました、ありがとうございます!

4

2 に答える 2

4

JsonHttpRequestInitializer をビルダーに追加し、そこにキーを設定してみてください。

Calendar service = Calendar.builder(transport, new JacksonFactory())
.setApplicationName("My Application's Name")
.setHttpRequestInitializer(accessProtectedResource)
.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
    public void initialize(JsonHttpRequest request) {
        CalendarRequest calRequest = (CalendarRequest) request;
        calRequest.setKey("myCalendarSimpleAPIAccessKey");
    }

}).build();
于 2011-12-10T19:42:47.877 に答える
1

いいえ10に答えるには:私は基本的にあなたがTaskSampleで作業しなければならなかったことをしなければならなかったし、次にここで入手可能なAndroid GDataカレンダーサンプルを使用しなければなりませんでした: client/source/browse/calendar-android-sample/src/main/java/com/google/api/client/sample/calendar/android/CalendarSample.java?repo=samples を使用して、AccountManager 自体から AuthToken を取得します。

accountManager = new GoogleAccountManager(this);
settings = this.getSharedPreferences(PREF, 0);
gotAccount();

private void gotAccount() {
        Account account = accountManager.getAccountByName(accountName);
        if (account != null) {
            if (settings.getString(PREF_AUTH_TOKEN, null) == null) {
                accountManager.manager.getAuthToken(account, AUTH_TOKEN_TYPE,
                        true, new AccountManagerCallback<Bundle>() {

                            @Override
                            public void run(AccountManagerFuture<Bundle> future) {
                                try {
                                    Bundle bundle = future.getResult();
                                    if (bundle
                                            .containsKey(AccountManager.KEY_INTENT)) {
                                        Intent intent = bundle
                                                .getParcelable(AccountManager.KEY_INTENT);
                                        int flags = intent.getFlags();
                                        flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK;
                                        intent.setFlags(flags);
                                        startActivityForResult(intent,
                                                REQUEST_AUTHENTICATE);
                                    } else if (bundle
                                            .containsKey(AccountManager.KEY_AUTHTOKEN)) {
                                        setAuthToken(bundle
                                                .getString(AccountManager.KEY_AUTHTOKEN));
                                        // executeRefreshCalendars();
                                    }
                                } catch (Exception e) {
                                    handleException(e);
                                }
                            }
                        }, null);
            } else {
                // executeRefreshCalendars();
            }
            return;
        }
        chooseAccount();
    }

private void chooseAccount() {
    accountManager.manager.getAuthTokenByFeatures(
            GoogleAccountManager.ACCOUNT_TYPE, AUTH_TOKEN_TYPE, null,
            ExportClockOption.this, null, null,
            new AccountManagerCallback<Bundle>() {

                @Override
                public void run(AccountManagerFuture<Bundle> future) {
                    Bundle bundle;
                    try {
                        bundle = future.getResult();
                        setAccountName(bundle
                                .getString(AccountManager.KEY_ACCOUNT_NAME));
                        setAuthToken(bundle
                                .getString(AccountManager.KEY_AUTHTOKEN));
                        // executeRefreshCalendars();
                    } catch (OperationCanceledException e) {
                        // user canceled
                    } catch (AuthenticatorException e) {
                        handleException(e);
                    } catch (IOException e) {
                        handleException(e);
                    }
                }
            }, null);
}

void setAuthToken(String authToken) {
    SharedPreferences.Editor editor = settings.edit();
    editor.putString(PREF_AUTH_TOKEN, authToken);
    editor.commit();
    createCalendarService(authToken);
    try {
        Events events = service.events().list("primary").execute();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

private void createCalendarService(String authToken) {
    accessProtectedResource = new GoogleAccessProtectedResource(authToken);

    Log.i(TAG, "accessProtectedResource.getAccessToken() = "
            + accessProtectedResource.getAccessToken());
    JacksonFactory jsonFactory = new JacksonFactory();
    service = com.google.api.services.calendar.Calendar
            .builder(transport, jsonFactory)
            .setApplicationName("Time Journal")
            .setJsonHttpRequestInitializer(
                    new JsonHttpRequestInitializer() {
                        @Override
                        public void initialize(JsonHttpRequest request) {
                            CalendarRequest calendarRequest = (CalendarRequest) request;
                            calendarRequest
                                    .setKey("<YOUR SIMPLE API KEY>");
                        }
                    }).setHttpRequestInitializer(accessProtectedResource)
            .build();
}
于 2011-12-23T20:35:58.187 に答える