Simplest Android Activity Lifecycle

前端 未结 9 1283
礼貌的吻别
礼貌的吻别 2020-12-13 20:28

I noticed that the Android Developers Activity section has been updated since I started my app, but I am still unclear what the simplest Activity Lifecycle is.

As fa

相关标签:
9条回答
  • 2020-12-13 20:41

    There are 7 methods that manage the activity lifecycle in Android application:

    1. onCreate()
    2. onStart()
    3. onResume()
    4. onRestart()
    5. onPause()
    6. onStop()
    7. onDestroy()

    I have written more in-depth about these methods on my blog

    0 讨论(0)
  • 2020-12-13 20:43

    Are you looking for this?

    To further answer your question, yes, as you can plainly see from the above diagram the "simplest" (i.e. smallest number of method calls) lifecycle is indeed onCreate(); onStart(); onResume(); onPause();.

    You should also know about onSaveInstanceState() and onRetainNonConfigurationInstance(). These are NOT lifecycle methods.

    All these methods are very well documented. Please read this documentation thoroughly.

    To clarify things further, here are a couple of real-life scenarios:

    1. Activity is running, other activities come on top of it, onPause is called. System runs out of memory, calls onSaveInstanceState, kills activity. User pressed back a few times, activity has to be re-instantiated (preferably using the data saved in onSaveInstanceState).
    2. Activity is running, user presses back. At this point onPause->onDestroy are called, without calling onSaveInstanceState.

    You should understand the essential difference between onPause and onSaveInstanceState. The former is always called, while the latter is only called when the activity instance might be re-instantiated in the future. Following this train of thought, your users will expect two things:

    1. When they navigate away from your Activity and later come back to it, they want it in the exact same instance that they left it (this would be achieved using onSaveInstanceState). They don't expect that if they exit your activity. However:
    2. They will expect that data they have entered will be persisted (which will be done in onPause). For example, if they started composing a message, they'll expect to see it as a draft the next time they come back, even if they exited the activity.

    You should understand how these methods are supposed to be used in order to get what your users expect. How you actually use them is up to you, your needs, and your app's nature.

    0 讨论(0)
  • 2020-12-13 20:44

    Android system is handling the lifecycle: i.e. instantiating activities and calling lifecycle methods. So I don't know what you mean by "destroy the activity". You, as a developer, have no such ability.

    Second, activity lifecycle flow can be sometimes confusing (I know I struggled with it at the beginning). So, just implement all lifecycle methods and put logging statements in them. Then try all real-life use cases (including receiving a call during app use) to see how lifecycle methods are called.

    0 讨论(0)
  • 2020-12-13 20:47

    What i personally think is developer should divide the work into different states of the activity. Sequence of the work must be retained in this case what is more importent I think of and this is why because Android can't handle a long UI processing in a single thread & it gives error that Android have 'so much work to do' in this reference that could be cause of getting crash sometimes So we should prevent to write whole code in a section. The code would be written into difference functions or classes and we can derive these functions as per requirement. Thanks.

    0 讨论(0)
  • 2020-12-13 20:48

    I was studying the activity life cycle and the complete process of what happens when you start any activity, starting from onCreate. Here is a UML diagram to help you.

    Click this link to see a High Resolution version.

    enter image description here

    0 讨论(0)
  • 2020-12-13 20:52

    The mature, full-featured and full functional Android app gets transitioned (state = function of time) according to the answer provided by @Felix.

    But what if you just want to create an app which doesn't even have GUI. And you want the simplest lifecycle then I have the answer below.

    This answer probably you would find interesting. Android system after reading AndroidManifest.xml knows which is entry point. Whichever activity has this

    <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    

    will be the starting or entry point for the system to start with. After this, your app process got the memory where it can start itself.

    Your main process creation is the task of Android system. When an application component starts and the application does not have any other components running, the Android system starts a new Linux process. After the process calls the onCreate(), it creates main thread. That's the reason why you must call onCreate(), because the main thread is then initialized and the main thread is the trigger for all of your future actions.

    On onCreate(), you got your main thread. After that, it is totally up to you, what callbacks you want to call. There is no rule you must call onStart() after onCreate().

    Only one lifecycle method onCreate() is guaranteed to be your component's life cycle back.

    And, furthermore, to understand, what each lifecycle method is doing inside it, put the below code.

    //add the log line
            Log.i(this.getClass().getCanonicalName(), "##############");
            int count = 0;
            for (StackTraceElement stackTraceElement:  Thread.currentThread().getStackTrace()) {
                count++;
                Log.i(this.getClass().getCanonicalName(), "\""+Thread.currentThread().getStackTrace()[2].getMethodName()+"\" "+count+" "+stackTraceElement.getMethodName());
            }; //end of log line
    

    So, always add above same code to view logs in log cat console.

    When your app starts GUI, it calls onStart(). If you don't call super() method inside the callback, android system shows broken pipe error and it can't do further processing and debugging.

    But, you can implement your own logic inside each callback method. Eg, you can do summation of two numbers on onStart().

    So, all android callback methods are partially implemented methods. They are not purely abstract methods because you should call the super() method inside them.

    The attached picture tells: Application main process calls onCreate(), it delegates it's responsibilities to main thread (UI thread) and main thread calls these 16 other callbacks.

    Further, if you would like to see all of your methods at particular time, put this below code.

    //to see all the methods (including super methods) at this time, you call use the java reflection as below
        Log.i(this.getClass().getCanonicalName(), "##############");
        int count1 = 0;
        for (Method method:  this.getClass().getMethods()) {
            count1++;
            count++;
            Log.i(this.getClass().getCanonicalName(), count1+" "+method);
        }; //end of log line
    
        //At another time, after you add some other methods or android using GC removes some methods, you see your changed state (Bundle Snapshot) of your class
        //Because your bundle (i.e, the state of your class/activity) is the function of time.
    

    In my scenario, from the just above code snippet, I see it has called 375 methods.

    Note: If you had added another method inside onCreate() before you print all of your methods using just above code snippet, you would have seen that method as well. It means, your state of the class (i.e., snapshot) is according to you, what you do time after time, you keep updating your snapshot.

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