Android - How To Override the “Back” button so it doesn't Finish() my Activity?

后端 未结 10 1164
粉色の甜心
粉色の甜心 2020-11-22 08:07

I currently have an Activity that when it gets displayed a Notification will also get displayed in the Notification bar.

This is so that when the User presses home a

10条回答
  •  -上瘾入骨i
    2020-11-22 08:45

    I think what you want is not to override the back button (that just doesn't seem like a good idea - Android OS defines that behavior, why change it?), but to use the Activity Lifecycle and persist your settings/data in the onSaveInstanceState(Bundle) event.

    @Override
    onSaveInstanceState(Bundle frozenState) {
        frozenState.putSerializable("object_key",
            someSerializableClassYouWantToPersist);
        // etc. until you have everything important stored in the bundle
    }
    

    Then you use onCreate(Bundle) to get everything out of that persisted bundle and recreate your state.

    @Override
    onCreate(Bundle savedInstanceState) {
        if(savedInstanceState!=null){ //It could be null if starting the app.
            mCustomObject = savedInstanceState.getSerializable("object_key");
        }
        // etc. until you have reloaded everything you stored
    }
    

    Consider the above psuedo-code to point you in the right direction. Reading up on the Activity Lifecycle should help you determine the best way to accomplish what you're looking for.

提交回复
热议问题