Run App Twice To Work

前端 未结 4 1108

I\'m making an android app that test if certain security features on your phone are enabled. For example, if you have password log in enabled or if your data is encrypted on you

4条回答
  •  独厮守ぢ
    2021-02-05 08:20

    Using a static variable to check how many times onStart has been called isn't a good idea, because an app can be killed if Android needs more memory for other apps while still allowing the user to navigate back to the app. That would be the path through the red box in the picture below (http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle):

    enter image description here

    A static variable would be 0 again after that and your app would run the security check again. What you need to do is use an instance variable that you persist in onSaveInstanceState and restore in onCreate. In case the app is killed, onSaveInstanceState is called and you save your Activity's state. If the user goes back to the app, onCreate is called and the state would be restored. This works for all other cases too when the app isn't killed but the user just navigates away from the app and later re-opens it. Here's a simple example of an app saving and restoring:

    public class MainActivity extends Activity {
    
        private boolean mSecurityCheckDone;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            if (savedInstanceState != null) {
                mSecurityCheckDone = savedInstanceState.getBoolean("mSecurityCheckDone");
            }
        }
    
        @Override
        protected void onStart() {
            super.onStart();
    
            if (! mSecurityCheckDone) {
                // run the security check
    
                mSecurityCheckDone = true;
            }
        }
    
        @Override
        public void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
    
            outState.putBoolean("mSecurityCheckDone", mSecurityCheckDone);
        }
    
        @Override
        public void onRestoreInstanceState(Bundle savedInstanceState) {
            super.onRestoreInstanceState(savedInstanceState);
    
            if (savedInstanceState != null) {
                mSecurityCheckDone = savedInstanceState.getBoolean("mSecurityCheckDone");
            }
        }
    
    }
    

提交回复
热议问题