Reputation: 143
*I have created a main Activity and login activity.
*My app will redirect user to login activity when they click on logout button but, problem is when I click on back it still goes to main activity which I don't want my app to do.
*According to me writing some condition with back button listener will help in some way. Is there any other solution to prevent this?
Upvotes: 1
Views: 3310
Reputation: 17085
When you start the login activity , you can clear all the other Activity
in stack using Intent.FLAG_ACTIVITY_CLEAR_TASK
flag.
FLAG_ACTIVITY_CLEAR_TASK
flag will cause any existing task that would be associated with the activity to be cleared before the activity is started
. i.e., the activity becomes the new root and any old activities are finished. This flag can only be used in conjunction with FLAG_ACTIVITY_NEW_TASK
Example :
Intent intent = new Intent(this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
Note: After you close the LoginActivity
using back and if you launch from `Activity History' the LoginActivity will be launched(not the MainActivity)
Upvotes: 4
Reputation: 7108
To make the back button always exit the app when in LoginActivity:
@Override
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
super.onBackPressed();
}
To remove the MainActivity from the task stack when redirecting:
Intent intent = new Intent(MainActivity.this,
LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
Upvotes: 1
Reputation: 26198
When you logout make sure that the your main activity is not overlapping with your login activity
Solution:
Intent intent = new Intent(this,LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
finish();
startActivity(intent);
FLAG_ACTIVITY_CLEAR_TOP: If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.
Upvotes: 1