FinishAndRemoveTask () is available by API 21

I would terminate my application and cancel it from the recent task list.

finishAndRemoveTask() is only available for API 21.

What should I use in the API below 21 ??

+5
source share
2 answers

Bet on the first activity on the stack and complete the current activity:

 Intent intent = new Intent(this, FirstActivity.class); intent.putExtra(EXTRA_FINISH, true); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); 

And in the onResume FirstActivity method, something like this to complete the last action on the stack (and hopefully remove the application from the list of recent applications):

 if (getExtras() != null && getIntentExtra(EXTRA_FINISH, false)) { finish(); } 
+3
source

I had a similar case when I needed to finish all the actions. Here is one way to do this without finishAndRemoveTask ().

Make all your activities an extension of the base class with the following things:

 private Boolean mHasParent = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (extras != null) { mHasParent = extras.getBoolean("hasParent", false); } } // Always start next activity by calling this. protected void startNextActivity(Intent intent) { intent.putExtra("hasParent", true); startActivityForResult(intent, 199); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (requestCode == 199 && resultCode == FINISH_ALL) { finishAllActivities(); } } protected void finishAllActivities() { if (mHasParent) { // Return to parent activity. setResult(FINISH_ALL); } else { // This is the only activity remaining on the stack. // If you need to actually return some result, do it here. Intent resultValue = new Intent(); resultValue.putExtra(...); setResult(RESULT_OK, resultValue); } finish(); } 

Just call finishAllActivities() on any action, and all actions will unfold. Of course, if you don't care what result the last action returns, the code can be made much simpler.

0
source

Source: https://habr.com/ru/post/1208613/


All Articles