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

痞子三分冷 提交于 2019-12-04 03:33:36

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..

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!