简体   繁体   English

登录后按后退按钮退出应用程序,但 OnPressedBack 继续返回首页

[英]Exit App When Pressed Back Button after Login, but OnPressedBack keep Coming Back to First Page

I have 3 activity the first one is LandingActivity.我有 3 个活动,第一个是 LandingActivity。 This is the launcher activity when you open the app and not logged in, the second is SignInActivity and the third is HomeActivity, this activity is launched when you're already logged in and open the app.这是您打开应用程序但未登录时的启动器活动,第二个是 SignInActivity,第三个是 HomeActivity,当您已经登录并打开应用程序时,将启动此活动。

Here's the code:这是代码:

LandingActivity登陆活动

 public class LandingActivity extends AppCompatActivity {

    private FirebaseAuth auth;
    private Button btnSignIn, btnSignUp;
    TextView textSlogan;

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

        //Init Firebase Auth
        auth = FirebaseAuth.getInstance();

        //Check if Already Session
        if (auth.getCurrentUser() != null){
            startActivity(new Intent(LandingActivity.this, HomeActivity.class));
        }

        textSlogan = (TextView)findViewById(R.id.textSlogan);
        Typeface face = Typeface.createFromAsset(getAssets(),"fonts/NABILA.TTF");
        textSlogan.setTypeface(face);

        btnSignIn = (Button)findViewById(R.id.main_sign_in_button);
        btnSignUp = (Button)findViewById(R.id.main_sign_up_button);

        btnSignIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LandingActivity.this, SignInActivity.class));
            }
        });

        btnSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LandingActivity.this, SignUpActivity.class));
            }
        });
    }
}

SignInActivity登录活动

    public class SignInActivity extends AppCompatActivity {

    private EditText inputEmail, inputPassword;
    private FirebaseAuth auth;
    private ProgressBar progressBar;
    private Button btnSignIn, btnResetPassword;

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

        //Get Firebase Auth Instance
        auth = FirebaseAuth.getInstance();

        setContentView(R.layout.activity_sign_in);

        inputEmail = (EditText) findViewById(R.id.email);
        inputPassword = (EditText) findViewById(R.id.password);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        btnSignIn = (Button) findViewById(R.id.action_sign_in_button);
        btnResetPassword = (Button) findViewById(R.id.intent_reset_password_button);

        //Get Firebase auth instance
        auth = FirebaseAuth.getInstance();

        btnSignIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String email = inputEmail.getText().toString();
                final String password = inputPassword.getText().toString();

                if (TextUtils.isEmpty(email)) {
                    Toast.makeText(getApplicationContext(), "Enter Email Address", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(password)) {
                    Toast.makeText(getApplicationContext(), "Enter Password", Toast.LENGTH_SHORT).show();
                    return;
                }

                progressBar.setVisibility(View.VISIBLE);

                //Authenticate User
                auth.signInWithEmailAndPassword(email, password)
                        .addOnCompleteListener(SignInActivity.this, new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {
                                // If sign in fails, display a message to the user. If sign in succeeds
                                // the auth state listener will be notified and logic to handle the
                                // signed in user can be handled in the listener.
                                progressBar.setVisibility(View.GONE);
                                if (!task.isSuccessful()) {
                                    //There was an Error
                                    if (password.length() < 6) {
                                        inputPassword.setError(getString(R.string.minimum_password));
                                    } else {
                                        Toast.makeText(SignInActivity.this, getString(R.string.auth_failed), Toast.LENGTH_SHORT).show();
                                    }
                                } else {
                                    Intent intent = new Intent(SignInActivity.this, HomeActivity.class);
                                    startActivity(intent);
                                    finish();
                                }
                            }
                        });
            }
        });

        btnResetPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(SignInActivity.this, ResetPasswordActivity.class));
            }
        });
    }
}

HomeActivity家庭活动

 public class HomeActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private FirebaseAuth auth;
    private FirebaseAuth.AuthStateListener authStateListener;
    private ProgressBar progressBar;
    private long backPressedTime;
    private Toast backToast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
        navigationView.setNavigationItemSelectedListener(this);

        progressBar = (ProgressBar) findViewById(R.id.progressBar);

        //Get Firebase Auth Instance
        auth = FirebaseAuth.getInstance();

        //Get Current User
        final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

        authStateListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                if (user == null) {
                    //User Auth State is Changed - User is Null
                    //Launch Login Activity
                    startActivity(new Intent(HomeActivity.this, LandingActivity.class));
                    finish();
                }
            }
        };

    }

    @Override
    public void onBackPressed() {
        if (backPressedTime + 2000 > System.currentTimeMillis()){
            backToast.cancel();
            super.onBackPressed();
        } else {
            backToast = Toast.makeText(getBaseContext(), "Press Back again to Exit", Toast.LENGTH_SHORT);
            backToast.show();
        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.actbar_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem) {
        int id = menuItem.getItemId();
        progressBar.setVisibility(View.VISIBLE);
        switch (id) {
            case R.id.action_edit_password:
                startActivity(new Intent(HomeActivity.this, ChangePasswordActivity.class));
                progressBar.setVisibility(View.GONE);
                break;
            case R.id.action_sign_out:
                auth.signOut();
                progressBar.setVisibility(View.GONE);
                Toast.makeText(this, "Signed Out", Toast.LENGTH_SHORT).show();
                finish();
                startActivity(new Intent(HomeActivity.this, LandingActivity.class));
        }
        return super.onOptionsItemSelected(menuItem);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_home) {
            auth.getCurrentUser();
            startActivity(new Intent(HomeActivity.this, HomeActivity.class));
        } else if (id == R.id.nav_app_received) {

        } else if (id == R.id.nav_app_submitted) {

        } else if (id == R.id.nav_tutorial) {
            startActivity(new Intent(HomeActivity.this, TutorialActivity.class));
        } else if (id == R.id.nav_about_us) {
            startActivity(new Intent(HomeActivity.this, AboutUsActivity.class));
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

I've tried onBackPressed() method to exit the app if back button pressed, but it still comes back to the LandingActivity instead of exiting the app.如果按下后退按钮,我已经尝试过onBackPressed()方法退出应用程序,但它仍然返回到LandingActivity而不是退出应用程序。 So, how to exit the app when back button is pressed but the user did not log out.那么,如何在按下后退按钮但用户没有退出时退出应用程序。

After startActivity() methods in your LandingPage activity use the method finish() .在 LandingPage 活动中的 startActivity() 方法之后使用方法finish() An excellent explanation of the finish method is given here这里给出了完成方法的一个很好的解释

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM