从 Google+ 从其他 activity 注销

logout from Google+ from other activity

我最近实施了 Google+ API。我成功地通过了身份验证并进入了主 activity。我的问题是我想在操作栏菜单中包含一个 "LogOut" 选项,当用户返回时,系统会提示他再次登录。

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

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

谢谢,

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

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

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

两点,在主登录上activity您需要根据点击事件更改标志状态。

如果您想从其他 activity 上的 G+ 帐户注销,请务必先初始化 GoogleApiClient,否则您将遇到空对象引用异常。

希望对某人有所帮助...

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();

                        }

                    });
        }
    }
}

在公共 class 中定义 GoogleApiClient,然后它可以被您想要的任何其他 class 检索

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,例如:

在登录活动中...

    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();
                    }
                });
      }