Simplest Android Activity Lifecycle

前端 未结 9 1284
礼貌的吻别
礼貌的吻别 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:54

    onCreate() obviously first. Your activity can then enter onPause(). From there it could either onResume() or onDestroy(). That's the simplest path through the lifecycle that I know of.

    I had an activity that didn't have an onPause() method. Through an odd series of events I noticed in DDMS that my app wasn't visible, but it was still requesting freshAds from AdMob :) Nice battery sucker. That's since been resolved but reminded me how important the simple things are.

    0 讨论(0)
  • 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!

    0 讨论(0)
  • 2020-12-13 20:58

    The answer is as simple as the life cycle. Only override callbacks when you need to handle stuff in there.

    Android will always call every callback how it is supposed to, except in certain circumstances.

    Just because certain callbacks are not guaranteed to be called doesn't mean that they are useless. Just don't try to handle sensible stuff in such callback methods.

    0 讨论(0)
提交回复
热议问题