user2568702
user2568702

Reputation:

Logout and Close all activities in Android

Login > HomePage ->Activity1 ->Activity2->Activity3

If once I have gone to Activity3 then from there to Home page. From there i am trying to logout. It is sending me back to the Login page but if I am pressing the back button of my phone it it showing all the previous activities. Please help me on how can we do this.

This is what i have tried

logout.setOnClickListener(new OnClickListener() {    
    @Override
    public void onClick(View arg0) {
        SharedPreferences myPrefs = getSharedPreferences("SelfTrip", MODE_PRIVATE);
        SharedPreferences.Editor editor = myPrefs.edit();
        editor.clear();
        editor.commit();
        Log.d(TAG, "Now log out and start the activity login");
        Intent loginPageIntent = new Intent(getApplicationContext(), LoginPage.class);
        loginPageIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
        loginPageIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(loginPageIntent);

    }
});

Upvotes: 3

Views: 11918

Answers (4)

Abhijit S
Abhijit S

Reputation: 181

// check sharedPreferences in all activities
// when you press back button then it will close activity
@Override
protected void onResume() {
    super.onResume();
    int userId = sharedPreferences.getInt(Login.user_id, 0);

    if(userId==0){
        finish();
    }
}

Upvotes: 3

droid
droid

Reputation: 414

You can use another way i.e adding activity in an arraylist of type activity and finish the activity you want from any other activity.

Upvotes: 0

bofredo
bofredo

Reputation: 2348

you can simply force the activity to NOT leave a history in your backstack. This can cause trouble, but should work fine as long as your activities are called linear.

Add the line with noHistory to the manifest:

<activity
        android:name="com.example.MainActivity"
        android:label="@string/app_name"           
        android:screenOrientation="portrait"

        android:noHistory="true" >
</activity>

Upvotes: 1

gunar
gunar

Reputation: 14710

Login activity needs to have android:launchMode="singleTop" in Manifest file. Here's the link for stack and back stack.

You also need to remove loginPageIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); as that will create a new task and put Login as root.

Upvotes: 3

Related Questions