Intent.FLAG_ACTIVITY_CLEAR_TOP doesn't deletes the activity stack

后端 未结 10 886
遇见更好的自我
遇见更好的自我 2020-12-17 09:20

I am developing the application in which i want to close whole application on button click. I know in android we should not think about to close the application because andr

10条回答
  •  [愿得一人]
    2020-12-17 10:15

    From documentation for Intent.FLAG_ACTIVITY_CLEAR_TOP

    If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.

    So to get it work your FinishActivity must be first one in your Activity stack. In any other cases this solution wouldn't give you anything.

    You must perform several steps to perform this:

    1) Make FinishActivity as your launcher activity.

    2) Do not provide any view for it and start first Activity of your application directly from onCreate callback :

    3) Redefine onRestart callback:

    Code sample:

    private boolean isNeedToContinue = true;
    
    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        if (isNeedToContinue) {
                        startActivity(new Intent(this,FirstVisibleActivity.class));
                        isNeedToContinue = false;
        } else {
            finish();
        }
    }
    
    @Override
    protected void onRestart() {
        super.onRestart();
        finish();
        isNeedToContinue = false;
    }
    

    I guess this is all you need. Good luck!

提交回复
热议问题