Override back button to act like home button

后端 未结 10 569
小鲜肉
小鲜肉 2020-11-22 08:38

On pressing the back button, I\'d like my application to go into the stopped state, rather than the destroyed state.

In the Android docs it states:

10条回答
  •  隐瞒了意图╮
    2020-11-22 09:01

    Most of the time you need to create a Service to perform something in the background, and your visible Activity simply controls this Service. (I'm sure the Music player works in the same way, so the example in the docs seems a bit misleading.) If that's the case, then your Activity can finish as usual and the Service will still be running.

    A simpler approach is to capture the Back button press and call moveTaskToBack(true) as follows:

    // 2.0 and above
    @Override
    public void onBackPressed() {
        moveTaskToBack(true);
    }
    
    // Before 2.0
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(true);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    

    I think the preferred option should be for an Activity to finish normally and be able to recreate itself e.g. reading the current state from a Service if needed. But moveTaskToBack can be used as a quick alternative on occasion.

    NOTE: as pointed out by Dave below Android 2.0 introduced a new onBackPressed method, and these recommendations on how to handle the Back button.

提交回复
热议问题