how to finish all activities and close the application in android?

回眸只為那壹抹淺笑 提交于 2019-11-30 17:25:24
Ragaisis

There is finishAffinity() method that will finish the current activity and all parent activities, but it works only in Android 4.1 or higher.

Loi Ho

This works well for me.

  • You should using FLAG_ACTIVITY_CLEAR_TASK and FLAG_ACTIVITY_NEW_TASK flags.

    Intent intent = new Intent(SecondActivity.this, CloseActivity.class);
    //Clear all activities and start new task
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); 
    startActivity(intent);
    
  • onCreate() method of CloseActivity activity.

    @Override 
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        finish(); // Exit 
    }
    
Avnish Choudhary

To clear all the activities while opening new one then do the following:

Intent intent = new Intent(getApplicationContext(), YourActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

This works well for me in all versions. Close all the previous activities as follows:

Intent intent = new Intent(this, HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // this will clear all the stack
intent.putExtra("Exit me", true);
startActivity(intent);
finish();

Then in HomeActivity onCreate() method add this to finish the MainActivity

setContentView(R.layout.main_layout);

if( getIntent().getBooleanExtra("Exit me", false)){
    finish();
    return; // add this to prevent from doing unnecessary stuffs
}

Sometime finish() not working

I have solved that issue with

finishAffinity()

Do not use

System.exit(0);

It will finish app without annimation.

Use finishAffinity() method that will finish the current activity and all parent activities. But it works only for API 16+ mean Android 4.1 or higher.

API 16+ use:

finishAffinity();

Below API 16 use:

ActivityCompat.finishAffinity(this); //with v4 support library

To exit whole app:

finishAffinity(); // Close all activites
System.exit(0);  // Releasing resources

You can try starting the Screen 3 with Intent.FLAG_ACTIVITY_CLEAR_TASK http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_CLEAR_TASK

Add android:noHistory="true" in your activity manifest file.

There are 2 ways for solve your problem

1) call finish() after startActivity(intent) in every activity

2) set android:launchMode="singleInstance" in every tag in menifest file

i think 2nd way is best for solving problem but you can also use first way

Gökhan Aydın
public void onBackPressed() {
    super.onBackPressed();
    finishAffinity();
    System.exit(0);
}

may be this method is better usage to close all activity and clean device memory.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!