onPause() and onStop() in Activity

前端 未结 6 1353
借酒劲吻你
借酒劲吻你 2020-12-04 16:05

I am new to Android development and I am still not able to understand the onPause() and onStop() methods in an activity.

In my app, I have

6条回答
  •  既然无缘
    2020-12-04 16:45

    I'm not sure which emulator you are testing with, but onPause is the one method that is always guaranteed to be called when your Activity loses focus (and I say always because on some devices, specifically those running Android 3.2+, onStop is not always guaranteed to be called before the Activity is destroyed).

    A nice way to understand the Activity lifecycle for beginners is to litter your overriden methods with Logs. For example:

    public class SampleActivity extends Activity {
    
        /**
         * A string constant to use in calls to the "log" methods. Its
         * value is often given by the name of the class, as this will 
         * allow you to easily determine where log methods are coming
         * from when you analyze your logcat output.
         */
        private static final String TAG = "SampleActivity";
    
        /**
         * Toggle this boolean constant's value to turn on/off logging
         * within the class. 
         */
        private static final boolean VERBOSE = true;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if (VERBOSE) Log.v(TAG, "+++ ON CREATE +++");
        }
    
        @Override
        public void onStart() {
            super.onStart();
            if (VERBOSE) Log.v(TAG, "++ ON START ++");
        }
    
       @Override
        public void onResume() {
            super.onResume();
            if (VERBOSE) Log.v(TAG, "+ ON RESUME +");
        }
    
        @Override
        public void onPause() {
            super.onPause();
            if (VERBOSE) Log.v(TAG, "- ON PAUSE -");
        }
    
        @Override
        public void onStop() {
            super.onStop();
            if (VERBOSE) Log.v(TAG, "-- ON STOP --");
        }
    
       @Override
        public void onDestroy() {
            super.onDestroy();
            if (VERBOSE) Log.v(TAG, "- ON DESTROY -");
        }
    }
    

提交回复
热议问题