Google使用g-plus最新API登录并在Android中退出

时间:2016-08-06 10:09:35

标签: android google-plus google-api-client google-oauth2 google-plus-signin

我已经完成了与google plus登录和注销相关的一些stackoverflow问题。而且大多数都已经过时了。我无法实现我真正想要的东西。

我退出后,下次登录时,我希望用户选择可用的Google帐户再次登录。

我正在使用自定义登录和注销按钮。对于注销,我有两种情况,

    如果任何用户已在同一登录活动中登录,则
  1. 在登录前退出。
  2. 从不同的活动中退出。
  3. 这是我到目前为止实施的内容:

    public class LoginActivity extends AppCompatActivity implements OnClickListener{
    
        private static final int RC_SIGN_IN = 9001;
        private GoogleApiClient mGoogleApiClient;
        private ConnectionResult mGoogleConnectionResult;
        private Button login;
        private ProgressDialog mProgressDialog;
        private Context mContext;
        private String mUri;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mContext= LoginActivity.this;
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            setContentView(R.layout.login_layout);
    
            login= (Button) findViewById(R.id.lg_login_btn);
            login.setOnClickListener(this);
        }
    
        @Override
        public void onClick(View v) {
            if(isOnline(mContext)){
                if(v.getId()== R.id.lg_login_btn) {
                    if(mGoogleApiClient!=null){
                        mGoogleApiClient.disconnect();
                    }
                GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestScopes(new Scope(Scopes.PLUS_LOGIN))
                .requestEmail()
                .build();
    
        mGoogleApiClient = new GoogleApiClient.Builder(mContext.getApplicationContext())
                .enableAutoManage(this , mGPlusConnectionFailedListener)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .addApi(Plus.API)
                .build();
    
            signOutGPlus();
            Intent lSignInIntent= Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
            startActivityForResult(lSignInIntent, RC_SIGN_IN);
    
                }
            } else{
                showAlertDialog(mContext, "Error", "Please check internet connection");
            }
        }
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            logD("&&onActivityResult", "requestCode: "+requestCode);     // first
    
            if (requestCode == RC_SIGN_IN) {
                if(resultCode == RESULT_OK){
                    showProgressDialog();
                    getGPlusUserInfo(data);
                } else {
                    logD("&&onActivityResult", "requestCode: RESULT_ NOT Ok"+requestCode);
                }
            }
        }
    
        GoogleApiClient.OnConnectionFailedListener mGPlusConnectionFailedListener= new GoogleApiClient.OnConnectionFailedListener() {
            @Override
            public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                logD("&&mGPlusConnectionFailedListener", "onConnectionFailed");
            }
        };
    
        private void getGPlusUserInfo(Intent data){
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            handleSignInResult(result);
        }
    
        private void handleSignInResult(GoogleSignInResult result) {
            Log.d("&&handleSignInResult", "handleSignInResult:" + result.isSuccess());
            if (result.isSuccess()) {
                // Signed in successfully, show authenticated UI.
                String lDisplayName="";
                String lEmail="";
                String lFirstName="";
                String lLastName="";
                String lGender="";
    
                // G+
                if (mGoogleApiClient.hasConnectedApi(Plus.API)) {
                    logD("&&GPlusUserInfo", "&hasConnectedApi--------------------------------");
                    // Deprecated
                    Person person = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
                    if(null != person) {
                        logD("&&GPlusUserInfo", "&--------------------------------");
                        logD("&&GPlusUserInfo", "&Display Name: " + person.getDisplayName());
                    lDisplayName= person.getDisplayName();
                        logD("&&GPlusUserInfo", "Gender: " + person.getGender());
                        if(person.getGender()< MyHalConstants.GENDER.length){
                            lGender= MyHalConstants.GENDER[person.getGender()];
                        } else{
                            lGender= "Other";
                        }
                    }
                }
                GoogleSignInAccount acct = result.getSignInAccount();
    
                if(null != acct) {
                    if (null != acct.getDisplayName()) {
                        logD("&&GPlusUserInfo", "&Display Name: " + acct.getDisplayName());
                    }
                    lFirstName= acct.getGivenName();
                    lLastName= acct.getFamilyName();
                    // Views inside NavigationView's header
                    Uri uri = acct.getPhotoUrl();                  
                }
            } else {
                // Signed out, show unauthenticated UI.
                signOutGPlus();
            }
        }
    
    
        // sign - out 
        private void signOutGPlus(){
            logD("&&signOutGPlus", "signOutGPlus");
            if(null != mGoogleApiClient){
                mGoogleApiClient.connect();
                mGoogleApiClient.registerConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
    
                    @Override
                    public void onConnected(@Nullable Bundle bundle) {
                        if(mGoogleApiClient.isConnected()) {
                            logD("&&signOutGPlus", "inside");
                        Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                                new ResultCallback<Status>() {
                                        @Override
                                        public void onResult(@NonNull Status status) {
                                            logD("&&signOutGPlus", "onResult");
                                            if(mGoogleApiClient.isConnected()){
                                            mGoogleApiClient.clearDefaultAccountAndReconnect();
                                                mGoogleApiClient.disconnect();
                                        }
                                        // Deprecated
                                        /*Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
                                        //Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient);
                                        //revokeAccess();*/
                                        }
                                    }
                        );
                        }
                    }
    
                    @Override
                    public void onConnectionSuspended(int i) {
    
                    }
                });
            }
        }
    
    // Not used
        private void revokeAccess() {
        logD("&&revokeAccess", "revokeAccess");
        Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
                new ResultCallback<Status>() {
                        @Override
                        public void onResult(Status status) {
                            // ...
                        }
                    });
        }
    
        private void showProgressDialog() {
            if (mProgressDialog == null) {
                mProgressDialog = new ProgressDialog(this);
                mProgressDialog.setMessage(getString(R.string.loading));
                mProgressDialog.setIndeterminate(true);
            }
    
            mProgressDialog.show();
        }
    
        private void hideProgressDialog() {
            if (mProgressDialog != null && mProgressDialog.isShowing()) {
                mProgressDialog.hide();
            }
        }
    
        private void showAlertDialog(Context pContext, String pTitle, String pMessage){
            AlertDialog.Builder ldialogBuilder= new AlertDialog.Builder(pContext);
            ldialogBuilder.setTitle(pTitle)
                .setMessage(pMessage)
            .setPositiveButton("Ok", null);
            ldialogBuilder.show();
        }
    
        private void dismissDialog(){
            if(null != mProgressDialog){
                mProgressDialog.dismiss();
                mProgressDialog= null;
            }
        }
    }
    

    至于来自不同活动的退出,我遇到的答案都没有定义如何在新活动中初始化 mGoogleApiClient

    如果我实施以下代码,则退出:

    private GoogleApiClient mGoogleApiClient;
    
    // sign - out 
    private void signOutGPlusFromDifferentActivity(){
        logD("&&signOutGPlus", "signOutGPlus");
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestScopes(new Scope(Scopes.PLUS_LOGIN))
                .requestEmail()
                .build();
    
        mGoogleApiClient = new GoogleApiClient.Builder(mContext.getApplicationContext())
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .addApi(Plus.API)
                .build();
        if(null != mGoogleApiClient){
            mGoogleApiClient.connect();
            mGoogleApiClient.registerConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                @Override
                public void onConnected(@Nullable Bundle bundle) {
                    if(mGoogleApiClient.isConnected()) {
                        logD("&&signOutGPlus", "inside");
                        Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                                new ResultCallback<Status>() {
                                    @Override
                                    public void onResult(@NonNull Status status) {
                                        logD("&&signOutGPlus", "onResult");
                                        if(mGoogleApiClient.isConnected()){
                                            mGoogleApiClient.clearDefaultAccountAndReconnect();
                                            mGoogleApiClient.disconnect();
                                        }
                                    }
                                }
                        );
                    }
                }
                @Override
                public void onConnectionSuspended(int i) {
    
                }
            });
        }
    }
    

    它会抛出错误。

    通过从登录活动中删除退出部分,我可以从GPlus正确登录。

    摇篮:

    compile 'com.google.android.gms:play-services-auth:9.2.1'
    compile 'com.google.android.gms:play-services:9.2.1'
    

    注意:从登录活动我可以从google plus或face-book登录。

    活动A(从g +或fb登录)。

    登录后,用户将被定向到活动B,来自活动B的用户可以从相应的门户网站(g +或fb)注销。

    Facebook部分已经完成。只剩下就是g +。

    通过使用更新的GOOGLE LOGIN LOGOUT API,请帮助正确退出。

4 个答案:

答案 0 :(得分:1)

对于注销,您可以使用以下方法:

private void signOut() {
    Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback(
            new ResultCallback<Status>() {
                @Override
                public void onResult(Status status) {
                    Timber.d("Logged out");
                }
            });
}

登录时,您可以按照以下方法操作:

public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
    this.activity = activity;
    if (requestCode == RC_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        handleSignInResult(result);
    }

   /*For inintializing googleapiclient*/
    private void initGoogleClient() {

    gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();

    googleApiClient = new GoogleApiClient.Builder(activity)
            .enableAutoManage((FragmentActivity) activity /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .addOnConnectionFailedListener(this)
            .addApi(Plus.API)
            .addScope(new Scope(Scopes.PROFILE))
            .build();
}

private void signIn() {
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
    activity.startActivityForResult(signInIntent, RC_SIGN_IN);
}

答案 1 :(得分:0)

  

我退出后,下次登录时,我希望用户选择可用的Google帐户再次登录。

诀窍是在用户点击Google登录按钮登录后立即 clearDefaultAccountAndReconnect GoogleApiClient 这可确保您在点击“登录”按钮时始终显示所有可用的Google帐户。

第1步:初始化GoogleAPIClient并将onClickListener设置为Activity onCreate()

中的googleSignInButton
private GoogleApiClient mApiClient;

private void initializeGoogleSignIn() {
    GoogleSignInOptions signInOptions = new GoogleSignInOptions
            .Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestProfile()
            .build();

    mApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this, this)
            .addApi(Auth.GOOGLE_SIGN_IN_API, signInOptions)
            .build();

    SignInButton googleSignInButton = (SignInButton) findViewById(R.id.google_sign_in);

    googleSignInButton.setOnClickListener(this);
}

第2步:通过onClick()方法处理Google登录

@Override
public void onClick(View v) {

    switch (v.getId()) {
        case R.id.google_sign_in:

            if (mApiClient.isConnected()) {
                mApiClient.clearDefaultAccountAndReconnect();
            } else {
                mApiClient.connect();
            }

            Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mApiClient);
            startActivityForResult(signInIntent, RC_SIGN_IN);

            break;
    }
}

<强> MISCALLANEOUS

// Make sure you connect and disconnect the GoogleApiClient in onStart and onStop lifecycle methods
@Override
protected void onStart() {
    super.onStart();
    mApiClient.connect();
}

@Override
protected void onStop() {
    super.onStop();
    if (mApiClient.isConnected())
        mApiClient.disconnect();
}



 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);

            if (result != null && result.isSuccess()) {

                GoogleSignInAccount account = result.getSignInAccount();

                setAppPreferenceData(account.getId(), account.getEmail(), String.valueOf(account.getPhotoUrl()), account.getDisplayName());

                startActivity(new Intent(this, NavigationActivity.class));


                finish();
            } else {
                mProgressLayout.setVisibility(View.GONE);

                if (Utils.isNetworkAvailable(this))
                    Toast.makeText(this, "Google Authentication Failed! Please try again", Toast.LENGTH_SHORT).show();
                else
                    Toast.makeText(this, "Network Error! Please connect to your wifi.", Toast.LENGTH_LONG).show();
            }
        } 
    }

为什么在代码中需要这么多的回调方法?我想你的代码有点复杂了。 主要技巧是在用户尝试登录时断开并清除默认帐户,以确保始终显示有效的Google帐户列表。 我使用了相同的程序,经过了尝试,测试和工作。

我的应用中使用的登录状态只有一种回调方法。

public class SignInActivity extends AppCompatActivity implements
        GoogleApiClient.OnConnectionFailedListener {
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Toast.makeText(SignInActivity.this, "Google Play connection error", Toast.LENGTH_SHORT).show();
    mProgressLayout.setVisibility(View.GONE);
}

答案 2 :(得分:0)

  

我退出后,下次登录时,我希望用户选择可用的Google帐户再次登录。

只需在用户点击退出按钮时退出用户并撤消访问权限。下次,当用户尝试登录时,他/她将被要求选择他们喜欢的谷歌帐户。

由于您正在登录并退出不同的活动,因此您最终会遇到重复的代码。不要复制代码,只需使用帮助程序类并初始化Google SignIn Option和Google API Client。现在,只要您想使用Google API客户端,就可以初始化帮助程序类。

案例1。如果您想在登录前退出,请使用clearDefaultAccountAndReconnect

案例2。要退出用户(不管活动是什么),请使用Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback

这是项目的github link。如果你还有疑问,可以看看。

答案 3 :(得分:0)

  

这解决了我的问题:-

Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
            new ResultCallback<Status>() {
                @Override
                public void onResult(@NonNull Status status) {
                    Toast.makeText(context, "Success"+status.getStatusMessage(), Toast.LENGTH_SHORT).show();
                }
            });