如何使用Firebase在导航抽屉中从Google正确注销

时间:2018-07-16 20:56:18

标签: android

您好,有人可以帮我实现带有google登录,导航抽屉和注销的android应用。一旦选择在抽屉中注销,该应用就会关闭,您必须重新打开该应用才能看到登录屏幕。

public class GoogleLogInActivity extends BaseActivity  implements View.OnClickListener {
                private static String TAG = GoogleLogInActivity.class.getSimpleName();
                private static int RC_SIGN_IN = 0;
                private FirebaseAuth.AuthStateListener mAuthListener;

                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_google_log_in);

                    findViewById(R.id.sign_in_button).setOnClickListener(this);

                    mAuthListener = new FirebaseAuth.AuthStateListener() {
                        @Override
                        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {

                         mFirebaseUser = firebaseAuth.getCurrentUser();
                            // if !null then we have signed in and direct us to the next activity
                            if (mFirebaseUser != null) {
                                if(BuildConfig.DEBUG)
                                Log.d(TAG, "user logged in" + mFirebaseUser.getDisplayName());

                                // starts the next activity upon successfull sign in
                                  startActivity(new Intent(GoogleLogInActivity.this,
                                        Navigation_Activity.class));
                            } else{
                                if(BuildConfig.DEBUG)
                                    Log.d(TAG,"Signed out");
                            }
                        }
                    };
                }


                @Override
                protected void onStart() {
                    super.onStart();
                    mAuth.addAuthStateListener(mAuthListener);
                }

                @Override
                protected void onStop() {
                    super.onStop();
                    if(mAuthListener != null)
                        mAuth.removeAuthStateListener(mAuthListener);
                }

                @Override
                public void onClick(View v) {
                    switch (v.getId()){
                        case R.id.sign_in_button:
                            showProgressDialog();
                        signIn();
                    }
                }

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

                // Google sign in was success call firebaseAuthWithGoogle to get firebase Authentication
                @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.isSuccess()) {
                            // Google Sign In was successful, authenticate with Firebase
                            GoogleSignInAccount account = result.getSignInAccount();
                            firebaseAuthWithGoogle(account);
                        } else{
                            // Google Sign In failed
                            hideProgressDialog();
                            Log.d(TAG, "Google sign in failed");
                            Toast.makeText(GoogleLogInActivity.this
                                    ," Google Sign in failed!! ",
                                    Toast.LENGTH_SHORT).show();
                        }

                    }else
                        hideProgressDialog();
                }

                private void firebaseAuthWithGoogle(final GoogleSignInAccount account) {
                    if(BuildConfig.DEBUG)
                        Log.d(TAG,"firebaseAuthWithGoogle:" + account.getDisplayName());

                    AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null );
                    mAuth.signInWithCredential(credential)
                            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                                @Override
                                public void onComplete(@NonNull Task<AuthResult> task) {

                                    Log.d(TAG, "signInWithCredential:onComplete: " + task.isSuccessful());


                                    if(task.isSuccessful()){
                                        String photoUrl = null;

                                        if(account.getPhotoUrl() != null){
                                            photoUrl = account.getPhotoUrl().toString();
                                        }

                                        // constructor access for user data
                                        Users user = new Users(
                                                account.getDisplayName() + " " + account.getFamilyName(),
                                            account.getEmail(),
                                            photoUrl,
                                            FirebaseAuth.getInstance().getCurrentUser().getUid()
                                        );

                                        //Get firebase database instance for user infromation storage
                                        FirebaseDatabase db = FirebaseDatabase.getInstance();
                                        DatabaseReference userRef = db.getReference(Constants.USER_KEY);
                                        userRef.child(account.getEmail().replace(".",","))
                                                .setValue(user, new DatabaseReference.CompletionListener() {
                                                    @Override
                                                    public void onComplete(@Nullable DatabaseError databaseError, @NonNull DatabaseReference databaseReference) {
                                                        finish();
                                                    }
                                                });

                                        if(BuildConfig.DEBUG)Log.v(TAG, "FirebaseAuth success");
                                    }
                                    //
                                    else{
                                        // if sign in fails display a message to the user
                                        hideProgressDialog();
                                        Log.v(TAG,"SignInWithCredential", task.getException());
                                        Log.v(TAG, "Authentication failed");
                                        Toast.makeText(GoogleLogInActivity.this
                                                ,"Sign in failed!! verify network connection ",
                                                Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });

                }
            }



        public class Navigation_Activity extends AppCompatActivity implements NavigationView.
                OnNavigationItemSelectedListener {

            private DrawerLayout drawer;
            private ActionBarDrawerToggle toggle;

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

                //toolbar support to set our custom toolbar
                Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_id);
                setSupportActionBar(toolbar);

                // adds the burger icon to the toolbar
                drawer = (DrawerLayout) findViewById(R.id.drawerlayout_id);
                toggle = new ActionBarDrawerToggle(this,drawer,toolbar,R.string.nav_open_drawer,R.string.nav_close_drawer);

                // adds the drawer toggle to the drawer layout
                 //then call sync state to  to synchronise the icon on the toolbar with state of the drawer
                drawer.addDrawerListener(toggle);
                toggle.syncState();

                // listener for navigation view to fire click options events
                NavigationView navView = (NavigationView) findViewById(R.id.nav_view);
                navView.setNavigationItemSelectedListener(this);

                // use fragment transaction to display SearchFragment instance
              Fragment fragment = new SearchFragment();
              FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
              ft.add(R.id.contentframe_id,fragment);
              ft.commit();

            }

            // gets called when an item is clicked in the drawer
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                int id = item.getItemId();
                Fragment fragment = null;
                Intent intent = null;

                switch(id){
                    case R.id.nav_album:
                        intent = new Intent(this, AlbumActivity.class);
                        break;
                    case R.id.nav_single:
                        intent = new Intent(this, SinglesActivity.class);
                        break;
                    case R.id.nav_artist:
                        intent = new Intent(this, ArtistActivity.class);
                        break;
                    case R.id.nav_cart:
                        intent = new Intent(this, CartActivity.class);
                        break;
                    case R.id.nav_logout:
                        intent = new Intent(this, LogoutActivity.class);
                }
                // display appropriate fragment or activity depending on selected item in drawer
                if(fragment != null){
                    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                    ft.replace(R.id.contentframe_id,fragment);
                    ft.commit();
                }else{
                    startActivity(intent);
                }

                // close the drawer when user selects an item in the drawer
                DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawerlayout_id);
                drawer.closeDrawer(GravityCompat.START);
                return true;
            }

            // if drawer is open close it if the user press back button
            @Override
            public void onBackPressed() {
                DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawerlayout_id);

                if(drawer.isDrawerOpen(GravityCompat.START)){
                    drawer.closeDrawer(GravityCompat.START);
                }else{
                    super.onBackPressed();
                }
            }
        }


        public class BaseActivity extends AppCompatActivity implements
                       GoogleApiClient.OnConnectionFailedListener {

            protected FirebaseUser mFirebaseUser;
            protected GoogleApiClient  mGoogleApiClient;
            protected FirebaseAuth mAuth;
            private ProgressDialog mProgressDialog;
            private GoogleSignInOptions gso;

            @Override
            protected void onCreate(@Nullable Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);

                mAuth = FirebaseAuth.getInstance();
                // Check if user is signed in
                if(mAuth != null){
                    mFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
                }

                // Configure Google Sign In, the client ID is in the GOOGLE JSON FILE
                GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                        .requestIdToken(getString(R.string.default_web_client_id))
                        .requestEmail()
                        .build();

                // GoogleApiClient with access to the Google Sign-In API specified by gso
                mGoogleApiClient = new GoogleApiClient.Builder(this)
                        .enableAutoManage(this,this)
                        .addApi(Auth.GOOGLE_SIGN_IN_API,gso)
                        .build();
            }

            protected void showProgressDialog(){
                if(mProgressDialog == null){
                    mProgressDialog = new ProgressDialog(this);
                    mProgressDialog.setMessage(getString(R.string.loading)); // will pull loading string from strings.xml
                    mProgressDialog.setIndeterminate(true);
                }
                mProgressDialog.show();
            }

            public void hideProgressDialog() {
                if (mProgressDialog != null && mProgressDialog.isShowing()) {
                    mProgressDialog.dismiss();
                }
            }

            protected void signOut(){
                mAuth.signOut();

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

                                    Log.d("BaseAct","User Logged out");
                                } else {
                                    Log.d("BaseAct","SignOutFailed");
                                }
                            }
                        });
            }

            @Override
            protected void onDestroy() {
                super.onDestroy();
                hideProgressDialog();
            }


            @Override
            public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                Log.d("BaseAct","Error");
            }

        }

0 个答案:

没有答案