Reputation: 153
My app is intended to allow only logged in user to access the activities. If a user logs out, the Shared preference boolean isLogged in is set to false and the user should not access the rest of activities except the LoginActivity.
However, I am able to access all the previously opened activities by pressing the back button.
I would use finish();
while opening each activity but then I would like users to still use the back button while they're logged in.
I have tried solutions from other similar questions like
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
and on the onCreate()
of my LoginActivity I have added
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
}
When I press the logout option, the previous activity opens instead.
Any suggestions please help me?
Upvotes: 8
Views: 12012
Reputation: 55
To exit the app when back button pressed try to use following code also:
finishAffinity();
Upvotes: 0
Reputation: 788
I faced to a similar situation. As I figured out, even if I call the finish()
function in the beginning, the whole onCreate()
function get executed. Then it will finish. In my scenario, in the onCreate()
function, I call to another Activity. So even if the main activity finishes after onCreate()
, the second activity still exists. So my solution was,
private boolean finish = false;
in onCreate() of the main function,
if(intent.getBooleanExtra("EXIT", false)) {
finish();
finish = true;
}
and I put a check in all navigations
if(!finish) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
My exit function was,
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
Upvotes: 0
Reputation: 4182
Try this
You need to add these flag in Intent..
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("EXIT", true);
startActivity(intent);
finish();
Upvotes: 4
Reputation: 544
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
android.os.Process.killProcess(android.os.Process.myPid());
}
Upvotes: 3
Reputation: 3101
Try to add all activity in array and when you want to remove just remove it from array and finish that activity. see my answer here Remove activity from stack
Upvotes: 2
Reputation: 4152
You should use this flags, that clear your TASK and create a new one
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
Upvotes: 6