Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close all the activities of my application?

Tags:

android

I've got an application with several activities, for example:

Activity 1 --> Activity 2 --> Activity 3 --> Activity 4

And I would like to close all the activities from any activity and go back at home phone.

like image 373
José Carlos Avatar asked Mar 27 '11 23:03

José Carlos


3 Answers

You can achieve that by using BroadcastReceivers:

  • Create a BaseActivity like this:

public class BaseActivity extends Activity {
    private KillReceiver mKillReceiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mKillReceiver = new KillReceiver();
        registerReceiver(mKillReceiver,
            IntentFilter.create("kill", "spartan!!!"));
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mKillReceiver);
    }
    private final class KillReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    }
}

  • Make your activities extend that BaseActivity.
  • Whenever you want to clear the stack:

Intent intent = new Intent("kill");
intent.setType("spartan!!!");
sendBroadcast(intent);

like image 62
Cristian Avatar answered Oct 31 '22 14:10

Cristian


You can clear all the previous activities using the following flags :

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); 

I hope it will help you !

like image 31
tryp Avatar answered Oct 31 '22 15:10

tryp


Open up AndroidManifest.xml and find the activity that you would like to return to and add the following attribute

android:launchMode="singleTask"

For example, HomeActivity class might have this in android manifest

<activity android:name=".HomeActivity"
    android:launchMode="singleTask"/>

At any point, you can close all activities on top of this one by using startActivity the standard way, for example

startActivity(new Intent(this, HomeActivity.class));

If you normally pass extras to the intent, there's no need to do this as it will come back in whatever state it was before, and it's even accompanied by an animation like hitting the back button.

like image 32
Daniel Skinner Avatar answered Oct 31 '22 14:10

Daniel Skinner