从其他活动中退出Google+

时间:2015-06-01 15:45:09

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

我最近实施了Google+ API。我设法成功验证并继续前进到主要活动。我的问题是我想在操作栏菜单中包含一个“LogOut”选项,当用户回来时,系统会提示他再次登录。

我读了几个答案但是我无法实现它们。

您能否建议实施此解决方案的最佳方式并提出一个好的示例?

谢谢,

3 个答案:

答案 0 :(得分:1)

所以我设法解决了这个问题,我创建了下面的基类,并在所需的活动中继承了它,我测试了它并按预期工作。对于需要了解如何构建它的人,您可以使用以下代码。

关于主要登录活动的两点,您需要根据点击事件更改标志状态。

如果您想在其他活动中从G +帐户退出,请务必先启动GoogleApiClient,否则您将获得null对象引用异常。

希望能帮到某人......

public class BaseClass extends AppCompatActivity  implements 
        GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{

    /* Request code used to invoke sign in user interactions. */
    private static final int RC_SIGN_IN = 0;

    protected GoogleApiClient mGoogleApiClient;
    protected Context mContext;

    /* "mIntentInProgress" is A flag indicating that a PendingIntent is in progress and prevents
     * us from starting further intents.
     * True if we are in the process of resolving a ConnectionResult
     * "mSignInClicked" FLAG is True if the sign-in button was clicked.  When true, we know to resolve all
     * issues preventing sign-in without waiting.
     */

    public boolean mIntentInProgress;
    public boolean mSignInClicked;

    public String mPersonName;
    public String mImageUrl;
    public String mEmailAddress;

    public BaseClass(){

    }



     public void CreateClient(Context mContext){
        //Client builder that return GoogleAPI client, make the connection from the app to the G+ service
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)//add OnConnected and OnConnectionSuspended methods to control the connection state
                .addOnConnectionFailedListener(this) // add OnConnectionFaild listener in case connection was failed.
                .addApi(Plus.API)
                .addScope(Plus.SCOPE_PLUS_PROFILE)//profile permission from the user
                .addScope(Plus.SCOPE_PLUS_LOGIN)// login details from the user
                .build();
         mGoogleApiClient.connect();
     }


    @Override
    public void onConnected(Bundle bundle) {
        Log.i("google base class", "onConnected invoked");
        try {
            if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
                Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
                mPersonName= currentPerson.getDisplayName();
                mImageUrl=currentPerson.getImage().getUrl();
                mEmailAddress = Plus.AccountApi.getAccountName(mGoogleApiClient);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i("google base class", "onConnectionSuspended invoked");
        mGoogleApiClient.connect();
    }


    @Override
    public void onConnectionFailed(ConnectionResult result) {

        Log.i("google base class", "onConnectionFailed invoked");

        if (!mIntentInProgress) {
            if (mSignInClicked && result.hasResolution()) {
                // The user has already clicked 'sign-in' so we attempt to resolve all
                // errors until the user is signed in, or they cancel.
                try {
                    result.startResolutionForResult(this, RC_SIGN_IN);
                    mIntentInProgress = true;
                } catch (IntentSender.SendIntentException e) {
                    // The intent was canceled before it was sent.  Return to the default
                    // state and attempt to connect to get an updated ConnectionResult.
                    mIntentInProgress = false;
                    mGoogleApiClient.connect();
                }
            }
        }

    }

    public void onLogout() {

        Log.i("base class", "logout invoked");
        if (mGoogleApiClient.isConnected()) {
            Log.i("base class", "logout invoked");
            Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
            mGoogleApiClient.disconnect();
            mGoogleApiClient.connect();

        }
    }


    /**
     * Revoking access from google
     * */
    public void revokeGplusAccess() {
        if (mGoogleApiClient.isConnected()) {
            Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
            Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient)
                    .setResultCallback(new ResultCallback<Status>() {
                        @Override
                        public void onResult(Status arg0) {
                            Log.e("base class", "User access revoked!");
                            mGoogleApiClient.connect();

                        }

                    });
        }
    }
}

答案 1 :(得分:1)

在公共类中定义GoogleApiClient,然后可以通过任何其他类检索

public class UserSessionManager implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

        // Context
        private Context _context;

        // Google plus Client
        public GoogleApiClient mGoogleApiClient;

        // Constructor
        public UserSessionManager(Context context){
            this._context = context;

            GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestEmail()
                    .build();
            mGoogleApiClient = new GoogleApiClient.Builder(_context)
                    .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                    .addConnectionCallbacks(this).build();
            mGoogleApiClient.connect();
        }

        @Override
        public void onConnected(Bundle bundle) {
            Log.i("google base class", "onConnected invoked");

        }

        @Override
        public void onConnectionSuspended(int i) {
            Log.i("google base class", "onConnectionSuspended invoked");
            mGoogleApiClient.connect();
        }


        @Override
        public void onConnectionFailed(ConnectionResult result) {

            Log.i("google base class", "onConnectionFailed invoked");

        }
    }

只需像往常一样使用mGoogleApiClient,例如:

在LoginActivity中......

    UserSessionManager session = new UserSessionManager(getApplicationContext());

    private void googleSignIn() {
           Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(session.mGoogleApiClient);
           startActivityForResult(signInIntent, application.TAG_RESULTLOGINGOOGLE);
    }

在LogoutActivity中

      UserSessionManager session = new UserSessionManager(getApplicationContext());

      private void googleLogOut() {
           Auth.GoogleSignInApi.signOut(session.mGoogleApiClient).setResultCallback(
                new ResultCallback<Status>() {
                    @Override
                    public void onResult(Status status) {
                        Toast.makeText(_context, "G+ loggedOut", Toast.LENGTH_SHORT).show();
                    }
                });
      }

答案 2 :(得分:-1)

尝试将此代码放入您自己的按钮或您想要的任何事件中。

if (mGoogleApiClient.isConnected()) {
        Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
        mGoogleApiClient.disconnect();
        mGoogleApiClient.connect();
    }