Simplest Android Activity Lifecycle

前端 未结 9 1303
礼貌的吻别
礼貌的吻别 2020-12-13 20:28

I noticed that the Android Developers Activity section has been updated since I started my app, but I am still unclear what the simplest Activity Lifecycle is.

As fa

9条回答
  •  臣服心动
    2020-12-13 20:57

    I think I have found what I am looking for! (Me 1, Bono 0)

    This is for a single 'Game' activity which uses minimum methods to control a 'GameThread' thread which handles the game. It uses an additional 'GameData' class to hold data which is required to be persistent between activations.

    If the app loses focus (i.e. an incoming phone call, or the user clicks back etc.), Game saves the GameData to a file and exits. To resume, just start the app again and it goes right back to where you left off.

    The layout file 'game.xml' is a SurfaceView covering the whole screen

    Game.java:

    1. onCreate sets up the SurfaceHolder for the SurfaceView and creates the GameThread
    2. surfaceChanged calls GameThread.startThread to start the GameThread, if not already started, passing the screen size
    3. onPause calls GameThread.endThread to end the GameThread and ends this activity
    4. onTouch passes touch events to the GameThread.doTouch method

    GameThread.java:

    1. startThread sets up locally held data, loads GameData from file and starts the thread
    2. run is a standard game loop, calling fairly standard updatePhysics and drawScreen routines for each frame. After the game loop finished it saves the GameData to the file
    3. endThread stops the game loop in run and waits for it to finish
    4. doTouch actions touch events from the Game activity

    It seems to work. It does mean having to handle different screens (e.g. title screen, options, play and game over) in the one thread, but that's not the end of the world, IMHO.

    Maybe I'll publish the code on CodeReview (I'll update this if I do) and see if anyone's got any comments. Meanwhile, I'd better get coding the next Angry Birds!

提交回复
热议问题