Android - Prevent onResume() function if Activity is loaded for the first time (without using SharedPreferences)

Jack picture Jack · Mar 29, 2013 · Viewed 11.5k times · Source

In my current application the onResume function is triggered when I load an Activity for the first time . I looked into the Activity Lifecycle, but I didn't find a way to prevent this from happening.

Can I prevent the onResume() function from loading when an Activity is loaded for the first time, without using SharedPreferences?

Answer

The Good Giant picture The Good Giant · Mar 29, 2013

Firstly, as RvdK says, you should not modify the Android Activity lifecycle, you probably have to re-design your activity behavior in order to be compliant with it.

Anyway, this is the best way that I see:

1.Create a boolean variable inside your Activity

public class MyActivity extends Activity{
  boolean shouldExecuteOnResume;
  // The rest of the code from here..
}

2.Set it as false inside your onCreate:

public void onCreate(){
  shouldExecuteOnResume = false
}

3.Then in your onResume:

public void onResume(){
  if(shouldExecuteOnResume){
    // Your onResume Code Here
  } else{
     shouldExecuteOnResume = true;
  }

}

In this way your onResume will not be executed the first time (shouldExecuteOnResume is false) but it will be instead executed all the other times that the activity is loaded (because shouldExecuteOnResume will be true). If the activity is then killed (by the user or the system) the next time it will be loaded the onCreate method will be called again so onResume will not be executed, etc..