从 Google 登录集成 android 注销

Posted

技术标签:

【中文标题】从 Google 登录集成 android 注销【英文标题】:Logout from Google Sign In Integration android 【发布时间】:2016-07-01 20:28:02 【问题描述】:

我正在学习实施 Google 登录集成。 我正在关注Google Developers 的演示。 这是我的登录页面代码:

public class LoginActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener, View.OnClickListener 

    private Button btnSignOut, btnDisconnect;
    private SignInButton btnSignIn;
    private ProgressDialog mProgressDialog;
    private static final String TAG = "LoginActivity";
    private TextView mStatusTextView;
    GoogleApiClient mGoogleApiClient;
    private static final int RC_SIGN_IN = 9001;
    private Button btnNext;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        initInstances();

    

    private void initInstances() 

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this, this)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();

        mStatusTextView = (TextView) findViewById(R.id.status);
        btnSignOut = (Button) findViewById(R.id.sign_out_button);
        btnDisconnect = (Button) findViewById(R.id.disconnect_button);
        btnSignIn = (SignInButton) findViewById(R.id.sign_in_button);
        btnSignIn.setSize(SignInButton.SIZE_STANDARD);
        btnSignIn.setScopes(gso.getScopeArray());


        btnSignIn.setOnClickListener(this);
        btnSignOut.setOnClickListener(this);
        btnDisconnect.setOnClickListener(this);

    

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) 

        Log.d(TAG, "onConnectionFailed:" + connectionResult);
        Toast.makeText(LoginActivity.this, "" + connectionResult, Toast.LENGTH_SHORT).show();

    

    @Override
    public void onStart() 
        super.onStart();

        OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
        if (opr.isDone()) 
            // If the user's cached credentials are valid, the OptionalPendingResult will be "done"
            // and the GoogleSignInResult will be available instantly.
            Log.d(TAG, "Got cached sign-in");
            GoogleSignInResult result = opr.get();
            handleSignInResult(result);
         else 
            // If the user has not previously signed in on this device or the sign-in has expired,
            // this asynchronous branch will attempt to sign in the user silently.  Cross-device
            // single sign-on will occur in this branch.
            showProgressDialog();
            opr.setResultCallback(new ResultCallback<GoogleSignInResult>() 
                @Override
                public void onResult(GoogleSignInResult googleSignInResult) 
                    hideProgressDialog();
                    handleSignInResult(googleSignInResult);
                
            );
        
    

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

    // [START onActivityResult]
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) 
        super.onActivityResult(requestCode, resultCode, data);

        // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) 
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            handleSignInResult(result);
        
    

    private void handleSignInResult(GoogleSignInResult result) 
        Log.d(TAG, "handleSignInResult:" + result.isSuccess());
        if (result.isSuccess()) 
            // Signed in successfully, show authenticated UI.
            GoogleSignInAccount acct = result.getSignInAccount();
            mStatusTextView.setText(getString(R.string.signed_in_fmt, acct.getDisplayName()));
            updateUI(true);
            //Log.d(TAG, "photoUrl "+result.getSignInAccount().getPhotoUrl());
            Intent iNext = new Intent(LoginActivity.this, ProfileInfoActiviy.class);

            iNext.putExtra("userId", acct.getId());
            iNext.putExtra("userName", acct.getDisplayName());
            if (acct.getPhotoUrl() != null) 
                iNext.putExtra("userPhoto", acct.getPhotoUrl().toString());
            
            iNext.putExtra("userEmail", acct.getEmail());

            startActivity(iNext);

         else 
            // Signed out, show unauthenticated UI.

            updateUI(false);
        
    

    private void signIn() 
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
    

    // [START signOut]
    private void signOut() 
        Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                new ResultCallback<Status>() 
                    @Override
                    public void onResult(Status status) 
                        // [START_EXCLUDE]
                        updateUI(false);
                        // [END_EXCLUDE]
                    
                );
    
    // [END signOut]

    // [START revokeAccess]
    private void revokeAccess() 
        Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
                new ResultCallback<Status>() 
                    @Override
                    public void onResult(Status status) 
                        // [START_EXCLUDE]
                        updateUI(false);
                        // [END_EXCLUDE]
                    
                );
    


    private void updateUI(boolean signedIn) 
        if (signedIn) 
            findViewById(R.id.sign_in_button).setVisibility(View.GONE);
            findViewById(R.id.sign_out_and_disconnect).setVisibility(View.VISIBLE);
         else 
            mStatusTextView.setText(R.string.signed_out);
            findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
            findViewById(R.id.sign_out_and_disconnect).setVisibility(View.GONE);
        
    

    private void intentToInfo() 
       /* Intent iNext=new Intent(LoginActivity.this,ProfileInfoActiviy.class);
        startActivityForResult(iNext,);*/
    


    @Override
    public void onClick(View v) 
        switch (v.getId()) 
            case R.id.sign_in_button:
                signIn();
                break;
            case R.id.sign_out_button:
                signOut();
                break;
            case R.id.disconnect_button:
                revokeAccess();
                break;

        

    


在 Google Developers 演示中,他们解释了如何退出,但它来自同一活动。我想退出下一个/另一个活动,如下所示:

protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile_info_activiy);
        ButterKnife.bind(this);

        String uId = getIntent().getExtras().getString("userId");
        String uName = getIntent().getExtras().getString("userName");
        String uEmail = getIntent().getExtras().getString("userEmail");
        if (getIntent().getExtras().getString("userPhoto") != null) 
            uPhoto = getIntent().getExtras().getString("userPhoto");
        

        tvUserId.setText(uId);
        tvUserName.setText(uName);
        tvEmailId.setText(uEmail);

        loadImage(uPhoto);

        btnSignOut.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
              Toast.makeText(ProfileInfoActiviy.this, "Logged Out" ,                                        Toast.LENGTH_SHORT).show();
            
        );

我无法从这里注销,因为 mGoogleApiClient 将在此处为空。 有什么想法吗??

【问题讨论】:

为什么不在你的 onClick 中声明LoginActivity.signOut(); 我想你可以参考github.com/googlesamples/google-services/blob/master/android/…的示例代码 我只提到了那个。它没有提到如何从另一个活动中注销@BNK 【参考方案1】:

将以下代码放入任何活动中。 当用户点击注销按钮时试试这个:

 Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
               new ResultCallback<Status>() 
                   @Override
                   public void onResult(Status status) 


                   
               );

把这个放到onCreate():

 mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
                .addApi(Auth.GOOGLE_SIGN_IN_API)
                .build();

然后像这样覆盖onStart()

 @Override
    protected void onStart() 
        super.onStart();
        mGoogleApiClient.connect();
    

【讨论】:

我知道如何退出,但是对于另一个活动,mGoogleApiClient 将为空..!!【参考方案2】:

退出 Google 的最佳代码是

 val gsoBuilder = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail()
      activity?.let 
              GoogleSignIn.getClient(it, gsoBuilder.build())?.signOut()
                                

【讨论】:

以上是关于从 Google 登录集成 android 注销的主要内容,如果未能解决你的问题,请参考以下文章

在 android 应用程序中从 google 和 facebook 注销

如何使用google plus的accessToken从不同的活动中注销android中的用户

Google 使用 g-plus 最新 API 在 android 中登录和注销

另一个活动中的 Facebook 注销问题

Flutter Authentication 从登录屏幕到登录屏幕使用 Google 登录和注销

android应用集成google登录