I'm building one of my first android apps. I met this problem that everytime you change screen orientation, Android destroys the app and builds it up again (I know this is more complex, but this isn't the subject of this post.)
I am wondering if it is good idea to have a Game game
variable inside my MainActivity.java
that would simply implement Serializable
. This way I can do this:
public class MainActivity extends AppCompatActivity {
private MagicSquareGame game;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
game = MagicSquareGame.getEngine();
initEditTextReferences();
initButtonReferences();
updateSumResultsOnScreen();
}
(all the other stuff...)
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putSerializable("game", game);
Log.i("MSG", "saving Game");
super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
game = (MagicSquareGame) savedInstanceState.getSerializable("game");
updateSumResultsOnScreen();
Log.i("MSG", "loading Game");
}
Is this an okay approach? Code smell? What problems can I meet?
1 Answer 1
If this is a private project, where you're free to use alpha-staged libraries I'd strongly recommend you take a look at Android Architecture Components. A great talk about the subject was given at the recent Google I/O.
Restructuring your app's architecture and using Android Architecture component - the LifeData and LifecycleObserver in particular will very much ease the problem of having to deal with LifeCycle events (such as screen orientation change).
If you're writing a game, then the Component-based Architecture may be interesting for your purposes. You'll very likely come across it when investigating architectures suitable for Games (render loops etc).
The general idea is:
- Separation of concerns and improving testability. Ideally you should be able to unit-test your entire game with locally running Java tests and no UI necessary whatsoever. This however requires you to separate your Game instance from your activity - something I'd highly recommend either way.
- Making your game modular and plugging it together in the form of components (this architecture style is a matter of preference but lends itself quite well to games)
Let me know, if you want me to elaborate on any of the points I mentioned.
Explore related questions
See similar questions with these tags.
Parcelable
instead ofSerializable
because a) it's made for this purpose and b) performance bec ause a). \$\endgroup\$Application
which lives (at least) as long as the app runs. \$\endgroup\$