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

前端 未结 1 654
甜味超标
甜味超标 2021-02-20 11:37

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 preve

相关标签:
1条回答
  • 2021-02-20 12:42

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

    0 讨论(0)
提交回复
热议问题