Search code examples
androidandroid-event

What Android event is only called once until the activity is destroyed?


I'm looking for a single answer (but I might be asking the wrong question)

Question- does any event only get called once TOTAL until an activity is destroyed?

I ask because when my user rotates the phone to landscape oncreate and onstart are both invoked causing a reload of sorts.

I'm looking for an event that I could put behavior into that would only get run 1x (until the activity is killed)

Thank you in advance


Solution

  • If it is specific to the Activity just check your savedInstanceState parameter in the onCreate event. If it is null, run your code, if not, your code has already been run.

    Example:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        if(savedInstanceState == null) {
            // Run your code
        }        
    }
    

    savedInstanceState will always be null when onCreate is run for the first time, and it will be populated thereafter.