Sb Rahman
Sb Rahman

Reputation: 5

How to exit onBackPressed method in android studio?

I have developed an android apps that have a splash screen and a login page. The problem is when a user give credential and pressed log in button it open controlActivity. but when I pressed back button, I navigate to login page again If I pressed back button again I navigate to splash screen. How can I stop navigating to previous page, when user press back button then app should exit?

Upvotes: 0

Views: 1719

Answers (3)

Rudra Rokaya
Rudra Rokaya

Reputation: 685

Answer by @Sambhav Khandelwal should solve your problem. In your splash screen you need to do add flags with intent like:

Intent intent = new Intent(SplashScreenActivity.this, LoginActivity.class); //assuming your splash screen name as SplashScreenActivity and login as LoginActivity
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);

Or you can do without flags like below:

Intent intent = new Intent(SplashScreenActivity.this, LoginActivity.class);
startActivity(intent);
finish();

Upvotes: 0

Sambhav Khandelwal
Sambhav Khandelwal

Reputation: 3765

Why does it happen ?


This is happening because whenever you open another activity from intent, it creates it over it.

How to solve the problem?


  1. You can add a flag like this
Intent intent = new Intent(this, SecondActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);

OR

  1. You can finish it.
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
finish();

If you want to close the app onBackPressed, you can override the method. Add this to your activity.

@Override
public void onBackPressed(){
    finish();
    System.exit(0);
}

Doing this, the app will be closed on back pressed!

Upvotes: 1

Sergiy Khomyn
Sergiy Khomyn

Reputation: 148

You need to put a flag in the activity you want to be forgotten.

Intent intent = new Intent(this, Main2Activity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);

Upvotes: 0

Related Questions