finishAndRemoveTask() available on API 21

与世无争的帅哥 提交于 2019-12-04 22:01:06

问题


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

finishAndRemoveTask() is available only on API 21.

What should I use on API lower than 21??


回答1:


Make an intent to the first activity in the stack and finish 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 method of the FirstActivity, something like this to finish the last activity in the stack (and hopefully removing the app from the recent apps list):

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



回答2:


I had a similar use case where I needed to finish all activities. Here is one way to do it without finishAndRemoveTask().

Make all your activities extend a base class with the following things in it:

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();
}

Simply call finishAllActivities() in any activity, and all the activities will unwind. Ofcourse if you don't care what result the last activity returns, the code can be made much simpler.



来源:https://stackoverflow.com/questions/27368525/finishandremovetask-available-on-api-21

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