logout from Google+ from other activity

时光怂恿深爱的人放手 提交于 2019-12-24 13:17:33

问题


I have recently implemented the Google+ API. I managed to succesfully authenticated and move forward to the main activity. My issue is that I would like to include a "LogOut" option in the action bar menu and when the user comes back he will be prompted to login again.

I read several answers however I wasnt able to implement them.

can you please suggest the best way to implement this solution and suggest a good example?

Thanks,


回答1:


So I manage to solve the issue, i created the below base class and just inherited it over the needed activities, I tested and it worked as expected. to anyone who needs an idea on how to build it you can use the below code.

Two points, on the main login activity you will need to change the flags state according to the on click events.

if you like to logout from G+ account on other activity, make sure to initilize the GoogleApiClient first otherwise you will get null object reference exception.

hope that will help someone...

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

                        }

                    });
        }
    }
}



回答2:


Define GoogleApiClient in a common class, then it can be retrieved by any other class you want

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

        }
    }

Just use your mGoogleApiClient as you usually do, for example:

In LoginActivity...

    UserSessionManager session = new UserSessionManager(getApplicationContext());

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

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



回答3:


try putting this code in the click of your own button or whatever event you want.

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


来源:https://stackoverflow.com/questions/30577746/logout-from-google-from-other-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!