登录一次后,为什么我的GoogleApiClient无法正常工作?

时间:2014-07-31 14:06:47

标签: android google-play-services google-api-client

我已经为Google Plus登录实施了GoogleApiClient,并且第一次使用效果很好。如果我之后返回登录ActivityActivity将自行finish。有时候需要花一点时间,但大部分时间都是马上。我注意到,当我不在GoogleApiClient.connect中拨打Activity.onStart或注释掉GoogleApiClient.Builder.addConnectionCallbacks时,就没有崩溃,但显然我不能再使用G +登录了。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    mApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(Plus.API, Plus.PlusOptions.builder().build())
            .addScope(Plus.SCOPE_PLUS_LOGIN)
            .build();
}

@Override
protected void onStart() {
    super.onStart();
    if (mApiClient != null && !mApiClient.isConnecting()) {
        mApiClient.connect();
    }
}

@Override
protected void onStop() {
    super.onStop();
    if (mApiClient != null && mApiClient.isConnected()) {
        mApiClient.disconnect();
        mApiClient.unregisterConnectionCallbacks(this);
        mApiClient.unregisterConnectionFailedListener(this);
        mApiClient = null;
    }
}

我的回调也是标准的。

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case RC_SIGN_IN:
                mSignInProgress = resultCode == RESULT_OK ? STATE_SIGN_IN : STATE_DEFAULT;
                if (mApiClient != null && !mApiClient.isConnecting()) {
                    mApiClient.connect();
                }
                break;
        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        mSignInProgress = STATE_DEFAULT;
        ...
    }

    @Override
    public void onConnectionSuspended(int i) {
        if (mApiClient != null && !mApiClient.isConnecting()) {
            mApiClient.connect();
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        if (mSignInProgress != STATE_IN_PROGRESS) {
            mSignInIntent = connectionResult.getResolution();
            if (mSignInProgress == STATE_SIGN_IN) resolveLogin();
        }
        if (mApiClient != null) {
            mApiClient.disconnect();
        }
    }

private void resolveLogin() {
    if (mSignInIntent == null) return;
    try {
        mSignInProgress = STATE_IN_PROGRESS;
        startIntentSenderForResult(mSignInIntent.getIntentSender(), RC_SIGN_IN, null, 0, 0, 0);
    } catch (IntentSender.SendIntentException e) {
        mSignInProgress = STATE_SIGN_IN;
        if (mApiClient != null && !mApiClient.isConnecting()) {
            mApiClient.connect();
        }
    }
}

我所做的一切主要基于Google's example。所以,请说清楚。我登录一次就好了。之后,如果我再次启动Activity,则会在很短的时间后才Activity.finish

1 个答案:

答案 0 :(得分:0)

您是否考虑过使用BaseGameUtil,它非常易于设置,并且可以处理所有登录和退出,使用可选的登录/退出按钮,您可以按照this进行设置。我最近设置了它,它被证明是一组非常有用的功能。