Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Chapter 13 Activity and life cycle


May 21, 2021 Android SDK Getting started


Table of contents


Chapter 13 Activity and life cycle

The Activity lifecycle doesn't only take effect after the user runs the application, it also affects the different feedback users get when they cut out and cut back to the app. W hen we develop an app, the first thing to keep in mind is that users often switch between our app and other apps during execution. D epending on how the user operates, the same application sometimes runs in the foretime and sometimes in the background. Y ou must ensure that your application is able to do so and save and recover data in a timely manner during such switching. Again, this process is slightly different for certain applications -- such as functional components.

1. Callback method

The first step

To control how applications work when Actity is in different states, such as when users cut out or cut back to the app, you can choose from a variety of processing methods. T his approach is also known as the Activity lifecycle callback method. A ndroid calls these methods after our Activity enters a particular state, ensuring through a series of steps that our application sequence continues to work without losing data and without using non-essential resources when the user is not interacting with it. Each callback method brings our application into a possible state.

If you've been exposed to Java app programming before, you should have found that Android apps start up in a different way. U nlike Java apps that use the main method directly, Android first executes the onCreate method in the main Actity class when it starts. K eep in mind that we've designated this class as primary starter Actity in the manifest. A ctivity first recalls the onCreate method, which is equivalent to repeating the process after the user starts the application. This is when the onCreate method puts the application into the Create state.

The developer's guide provides an intuitive introduction to lifecycles, callback methods, and the concept of state through diagrams. W here the onResume method is responsible for providing the Resumed state, our program can accept the user's direct action. Various other callback methods are based on onResume, which directs the application to or from the Resumed state, starts it, or stops it.

For most applications, we only need to use a partial callback method, but at the very least we need onCreate. A lthough usage is not frequent, understanding the full callback and state role will help us understand how Android systems are affected when our applications are running and stopping running. In general, you need to ensure that users can smoothly return to their previous running state after switching out of any operation, and if they navigate forward or backward through navigation, the app needs to save all the necessary data and free up unnecessary hardware resources.

Step two

Our applications may be in five states: Create, Started, Resumed, Paused, and Stopped. T here are seven other callback methods that allow the app to enter or leave the above state: onCreate, onStart, onRestart, onResume, onPause, onStop, and onDestroy. T hese methods allow our applications to switch between possible states, and in some cases quickly. In general, one can think of your own application as always in the three states of resumed, paused, or stop, because the other states are temporary.

When our application is running and the user interacts with it, the app state is Resumed, and when another Actity is in the foreover but only partially hides our app, the app state is Paused -- a state in which the user can no longer interact with the app. W hen our app is completely in the background and the user can neither operate nor view it, the status is Stop. In this state, Actity retains all previous data, but cannot execute it.

2. Enter the Resumed state

As we know, the main Actity will start running when the application starts, and the onCreate method will execute, allowing us to prepare the Activity UI required for the class and all the data entries. M ost of the apps we create contain more than one Actity, which starts when the user interacts with the application. You can use the following code to start another non-master Actity through theIntent class:

Intent aboutIntent = new Intent(this, About.class);
startActivity(aboutIntent);

This represents another Actity class named "About" in the application package. Y ou can create a new Acty in Eclipse by selecting your own source package and then selecting File, New, Class, and then select the Android Activity class as a super class. K eep in mind that every Actity must be listed in our application list. You can also use the Innt class to transfer data between different Activities.

When an Activity is running, the onCreate method is executed at the same time, so in addition to listing other Actity classes, you can handle them in your application in a similar way to the main Activity. We can also create a layout file for each Activity and set it up to use the same technical mechanism as the main Actity.

After the execution of one of Active's onCreate methods begins, the onStart and onResume methods will also begin to execute, leaving the Actity in the Resumed state and transitioning to the Create and Started states as the case becomes during subsequent executions.

Our Activity can enter the Resumed state in more than one way, and application launch is just one of the most basic ways. I f Active is in the Paused or Stopped state, the Actity will go directly into foretime run mode after the application switches to the current one without having to call the onCreate method repeatedly. I f everyone's app switches back from paused to Resumed, Actity's onResume method starts executing. If the app switches back from the Speed state to the running state, the onRestart method is followed by the onStart and onResume methods.

3. Enter the Destroyed state

The first step

When our application is exited or hidden, Resumed becomes Testroyed. A t this point, the onPause method transitions the applied Activity from the Resumed state at runtime to the Passed state. I n onPause, you should stop any resource-intensive tasks, such as animation playback, sensor data processing, and broadcast reception. I f onPause is executing, then onStop can also start executing, as the user has usually exited our application by navigation. You can also use the onPause method for data preservation -- although data preservation is generally the most appropriate one for the onStop method.

As we mentioned earlier, Everyone's Activity can go back from the Passed state to the Resumed state with the onResume method. T his means that we can use onResume to recover anything we've stopped or posted in onPause before. However, it is also important to remember that onResume can be executed in other situations, such as when the application starts.

Step two

After onPause, if the application enters the Stop state, then onStop will also start executing. I n this case, methods such as onRestart, onStart, and onResume can still bring the application back to the Resumed state. I n onStop, you should compress as much as possible the amount of operations that are only necessary, such as writing content into a database. Make sure that all the resources used by your application are included in the onStop so that the app does not cause memory overflow problems after it is completely shut down.

The system saves specific data, such as what needs to be displayed in the view, after the application switches from the resumed state to the stopped state. W hen an Activity returns from the Stopped state to the Resumed state, the onRestart, onStart, and onResume methods all begin to execute. H owever, onStart performs differently from onResume -- for example, when the application starts. The onRestart method will only be executed after the application has recovered from the Stop state to the fore desk, so that everyone can use it to recover any running content saved in the onStop.

Tip: When everyone starts another Activity from under OneActivit, the former goes into the Stopped state. I f the user then uses the back button again by the latter to return to the previous Actity, the former's onRestart method will begin to execute.

Step three

If everyone's application is about to close completely, such as our current Activity being removed from the system, the onDestroy method will begin to execute. A lthough this is the last way to do it before our Activity disappears completely, you shouldn't simply clear everything. I n fact, we need to use onStop or onPause to get the job done. There are exceptions, of course, if the application's background process is still running, then you should stop it in onDestroy.

After onDestroy executes, if the user navigates back to the application Activity, the corresponding onCreate method is started again. I n general, you can pretend that onPause and onStop will be executed before onDestroy. However, if the finish method is explicitly called to end an Actity, only onDestroy will be executed.

In most cases, we don't need to put too much effort into lifecycle callbacks in our applications, because you can use the parameters of the onCreate method to preserve data. I n the Activity onCreate method, the Bundle parameter is responsible for automatically saving view information as described earlier. H owever, you can also use the object to hold more data content, such as variable updates that record interactions between users and applications. To achieve this, you can use the onSaveInstanceState method in theActivity class, and once we've written the data key value pairs, we can recover them in the onCreate.

Tip: When the user changes the device display mode, i.e. switching between portrait and landscape modes, our Actity actually undergoes re-creation and onCreate is re-performed. T his process is what we call configuration changes. I n this case, the system assumes that everyone needs to re-createActivity, for example, you use a different layout in each display mode. I n most cases, however, you may not want the system to do the same. T o avoid re-creating our Activity as the display mode transitions, you can choose between adding the "android:configChanges" property to activity in the manifest, or adjusting our Actity structure to take advantage of the Fragments we keep when we configure variables.

Summarize

As you begin to learn how to develop applications for the Android platform, the large number of states and callbacks involved in Activity can be a source of many challenges and even confusion. I n most cases, however, we only need to take the lowest amount of methods to ensure that our applications have the ability to deliver the functionality and results that users expect. I n the next part of this series, we'll take a look at some of the commonLy used Android classes, and you'll probably be dealing with them in your first app. After that, we'll look at the Android code samples, the application release knowledge you need to know, and other suggestions for further learning in the future.