问题
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?
回答1:
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..
来源:https://stackoverflow.com/questions/15701163/android-prevent-onresume-function-if-activity-is-loaded-for-the-first-time