How to make an activity stop, rather then be destroyed, from the BACK key?

前端 未结 7 1322
心在旅途
心在旅途 2020-12-15 07:02

Right now an activity gets destroyed when the BACK key is pressed. How can I make it just stop ( i.e. keep all the variables, etc. alive ), rather then be destroyed?

7条回答
  •  遥遥无期
    2020-12-15 07:29

    Pressing the BACK key triggers the onBackPressed callback method of Activity class. The default implementation of this callback calls the finish() method.

    http://developer.android.com/reference/android/app/Activity.html#onBackPressed()

    You can override this method to move the activity to background (mimick the action of pressing the HOME key.

    eg:

    
    @Override
    public void onBackPressed() {
        onKeyDown(KeyEvent.KEYCODE_HOME);        
    }
    

    You could also instead consider moveTaskToBackground() mentioned here:

    Override back button to act like home button

提交回复
热议问题