如何从另一个Activity或Fragment android注销GoogleApiClint

时间:2017-06-30 17:30:32

标签: android android-fragments google-oauth2 android-googleapiclient

我正在使用Google Api Clint登录Google帐户。我的代码工作正常,但是当我尝试从片段Logout.java注销时,它无法正常工作,请参阅下面的登录活动代码。

在oncreate中

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

        // Customizing G+ button
        btnSignIn.setSize(SignInButton.SIZE_STANDARD);
        btnSignIn.setScopes(gso.getScopeArray());

其余的代码

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

          if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            handleSignInResult(result);
        }
    }


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


    private void signOut() {
        Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                new ResultCallback<Status>() {
                    @Override
                    public void onResult(Status status) {
                        updateUI(false);
                    }
                });
    }

    private void revokeAccess() {
        Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
                new ResultCallback<Status>() {
                    @Override
                    public void onResult(Status status) {
                        updateUI(false);
                    }
                });
    }

    private void handleSignInResult(GoogleSignInResult result) {
        Log.d(TAG, "handleSignInResult:" + result.isSuccess());
        if (result.isSuccess()) {
            // Signed in successfully, show authenticated UI.
            GoogleSignInAccount acct = result.getSignInAccount();

            Log.e(TAG, "display name: " + acct.getDisplayName());

            String personName;
            //String personPhotoUrl = acct.getPhotoUrl().toString();
            String email;
            String gid;
            String location = "Location Not Set";
            String oarth = "Google";
            String gender = "Not Set";

            if(acct.getDisplayName() != null){
                personName = acct.getDisplayName();
            }else{
                personName ="";
            }
            if(acct.getEmail() != null){
                email = acct.getEmail();
            }else{
                email ="";
            }
            if(acct.getId() != null){
                gid = String.valueOf(acct.getId());
            }else{
                gid ="";
            }

            Log.e(TAG, "Name: " + personName + ", email: " + email
                    + ", id: " + gid +", location:" +location+", oarth: "+oarth+", gender: "+gender);

            //session.setMember(gid, personName, location, gender, email, oarth);
            InsertFbLogindata(gid, personName, location, gender, email, oarth);

            updateUI(true);
        } else {
            // Signed out, show unauthenticated UI.
            updateUI(false);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        switch (id) {
            case R.id.btn_sign_in:
                signIn();
                break;

            case R.id.btn_sign_out:
                signOut();
                break;

            case R.id.btn_revoke_access:
                revokeAccess();
                break;
        }

    }

    @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.
            showDialog();
            opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
                @Override
                public void onResult(GoogleSignInResult googleSignInResult) {
                    hideDialog();
                    handleSignInResult(googleSignInResult);
                }
            });
        }
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.d(TAG, "onConnectionFailed:" + connectionResult);
    }

    private void updateUI(boolean isSignedIn) {
        if (isSignedIn) {
            btnSignIn.setVisibility(View.GONE);
            btnSignOut.setVisibility(View.VISIBLE);
            btnRevokeAccess.setVisibility(View.VISIBLE);
        } else {
            btnSignIn.setVisibility(View.VISIBLE);
            btnSignOut.setVisibility(View.GONE);
            btnRevokeAccess.setVisibility(View.GONE);
        }
    }

在我的注销片段

public class logout extends Fragment {

    Button Logout;

    Session session;
    LoginActivity la;

    private GoogleApiClient mGoogleApiClient;
    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.sent_layout,container,false);
        final Button logout = (Button)root.findViewById(R.id.buttonLogout);
        logout.setOnClickListener(new View.OnClickListener() {
             public void onClick(View view) {
                session = new Session(getActivity());
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                       intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                       intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                       intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                  session.setLogin(false);
                  LoginManager.getInstance().logOut();

                 Auth.GoogleSignInApi.signOut(mGoogleApiClient);

                 Toast.makeText(getActivity(), "Logged Out", Toast.LENGTH_SHORT).show();
                startActivity(intent);
             }

        });
        return root;
    }

}

我尝试了很多例子但没有用。这有可能吗?请提出最佳方法。

1 个答案:

答案 0 :(得分:0)

你的活动代码绝对没问题,但在login.java中,你必须按如下方式更改一些代码。

  1. 获取googlesigninoptions的实例
  2. firebase身份验证
  3. 就是你可以叫`mAuth.signout()
  4.     GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.server_client_id))
                .requestEmail()
                .build();
        mGoogleSignInClient=GoogleSignIn.getClient(
    
        getActivity(),gso);
        mAuth=FirebaseAuth.getInstance();
            mGoogleSignInClient.signOut().
    
        addOnCompleteListener(getActivity(),
            new OnCompleteListener<Void>()
    
        {
            @Override
            public void onComplete (@NonNull Task < Void > task) {
            SharedPreferences getUser = getActivity().getSharedPreferences("user_info", getActivity().MODE_PRIVATE);
            SharedPreferences.Editor ed = getUser.edit();
            ed.putString("username", null);
            ed.commit();
            Snackbar.make(v.getRootView().findViewById(R.id.settings_fragment_layout), "Logged Out Successfully", Snackbar.LENGTH_SHORT).show();
            HomeFragment hf = new HomeFragment();
            getFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fragment_container, hf)
                    .commit();
        }
        });