Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clearing all activities in android

I have 4 Activities 1.Home,2.B,3.C and 4.D. Whenever I start Home from Activity D I want to finish all other activities. I Used this code, but when I press back button from Home it brings me to the previous activity. What I did wrong here.?

    Intent intent = new Intent(getApplicationContext(), Home.class);        
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent)

2 Answers

You can try this,

Intent intent = new Intent(getApplicationContext(), Home.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

Note: As described in FLAG_ACTIVITY_CLEAR_TOP documentation

This launch mode can also be used to good effect in conjunction with FLAG_ACTIVITY_NEW_TASK: if used to start the root activity of a task, it will bring any currently running instance of that task to the foreground, and then clear it to its root state. This is especially useful, for example, when launching an activity from the notification manager.

like image 78
Pradip Avatar answered May 14 '26 04:05

Pradip


intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

This will work only for activities which are still in the activity stack. I believe you are finishing the Home Activity when going to B. So that CLEARTOP won't work. Now try something like this.

You need to set an Extra with intent Of "D" to Home. Then you have to check the Intent extra in Home, call finish() if the extra matching

    Intent intent = new Intent(contxt, Home.class);
    intent.putExtra("urString",defaultvalue);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
    // Checking the intent extra at "HOME"
    if(getIntent().hasExtra("urString")){
      // manage your own way            
      finish();
    }
like image 42
Joyal Avatar answered May 14 '26 05:05

Joyal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!