How can I close my application on back pressed in android

后端 未结 12 1276
轻奢々
轻奢々 2021-01-14 00:04

I want to go on home screen when I press device\'s back button.I am using this code..

public void onBackPressed() {
   this.finish();
   return;
}

12条回答
  •  悲哀的现实
    2021-01-14 00:33

    Quoting from Official Guideline

    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.

    FLAG_ACTIVITY_CLEAR_TASK

    If set in an Intent passed to Context.startActivity(), this flag will cause any existing task that would be associated with the activity to be cleared before the activity is started. That is, the activity becomes the new root of an otherwise empty task, and any old activities are finished. This can only be used in conjunction with FLAG_ACTIVITY_NEW_TASK.

    FLAG_ACTIVITY_NO_HISTORY

    If set, the new activity is not kept in the history stack. As soon as the user navigates away from it, the activity is finished. This may also be set with the noHistory attribute.

    FLAG_ACTIVITY_NEW_TASK

    If set, this activity will become the start of a new task on this history stack.

    @Override
    public void onBackPressed()
    {
    
                    Intent intCloseApp = new Intent(Intent.ACTION_MAIN);
                    intCloseApp.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    intCloseApp.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                    intCloseApp.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    intCloseApp.addCategory(Intent.CATEGORY_HOME);
                    intCloseApp.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intCloseApp);
      }
    

提交回复
热议问题