Android app resets on orientation change, best way to handle?

后端 未结 5 576
余生分开走
余生分开走 2021-01-03 08:02

So I am making a basic chess app to play around with some various elements of android programming and so far I am learning a lot, but this time I am lost.

When the o

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-03 08:14

    Override onRetainNonConfigurationInstance in your Activity class.

    In this method you must return an object, just bundle up your game's state in a single state object and return it in this method. Make sure this is only a state object, by that i mean it should have no handles to an activity, view, etc. contained within it or you'll get memory leaking.

    In your onCreate method call getLastNonConfigurationInstance to get the object back.

    You don't have to worry about the implementation details (the serialization) android takes care of that.

    If you haven't already make sure you've set your Launch Mode in the manifest to either singleTask or singleInstance depending on which fits your needs better. By default if someone hits home and then comes back to your application it launches a new copy of the activity, if not handled or configured for single instance you'll get multiple copies of your game activity running.

提交回复
热议问题