Waddas
Waddas

Reputation: 1402

onSizeChanged() calls onCreate() and onStart()? - Android

My app currently calls a method within the onCreate() method so that the game will start and animations will run once the view is created. However when i flip the screen to switch between portrait and landscape, this method is called again.

I've moved the calling line both to the onStart() method and even the methods class constructor.

this is the method that is being called:

public void startGame() {
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {

        public void run() {
            runGame();
        }
    }, 500);
}

There is a delay to allow everything to be constructed before it is run, otherwise it won't work.

Is there i way to stop onSizeChanged() affecting this method being called? Or is there a way i can call this method so that it starts when the activity is started (again so that onSizeChanged() cant affect it and that everything is initialized before its call).

Thanks for looking.

Upvotes: 0

Views: 683

Answers (3)

pt2121
pt2121

Reputation: 11870

The easiest way is to add:

android:configChanges="orientation|screenSize"

which tells the system you'll take care of them yourself. However, it's not recommended.

Note: Using this attribute should be avoided and used only as a last-resort. Please read Handling Runtime Changes for more information about how to properly handle a restart due to a configuration change.

Or you can check savedInstanceState. If it is not null, that means a user changes the orientation (or the app are coming back from a configuration change). Maybe something likes this:

if(savedInstanceState == null)
    startGame();
else
    //handle a configuration change if necessary

Please see Don't reload application when orientation changes

Edit :

if(savedInstanceState == null) {
    startGame();
} else {
    //handle a configuration change if necessary
    int yourVar = savedInstanceState.getInt("something");
}

Upvotes: 1

Matt
Matt

Reputation: 367

Could you use a static thread variable instead of handler?

e.g.

  private static Thread gameThread = new Thread(new Runnable(){
        public void run()
        {
              //if necessary: Thread.sleep(500);
              runGame();
        }
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
        //rest of oncreate code here
        if(gameThread.isAlive() == false)
        {
              gameThread.start();
        }
  }

Upvotes: 0

Royi
Royi

Reputation: 755

add this to your manifest:

android:configChanges="screenSize"

Upvotes: 0

Related Questions