Managing the Activity Lifecycle
Android Activities and Life cycle, as a user moves through, away from, and back to an app, the Activity occurs in the app transition between various states in their lifecycle. For example, when your activity begins for the first time, it appears in the forefront of the system and receives user focus.
At this time, the Android system calls successions of lifecycle techniques on the activity in which you arrange the user interface and other constituents. If the user carries out an action that begins another activity or switches to an additional app, the system calls another set of lifecycle methods on your activity as it travels into the backdrop where the activity is no longer noticeable, but the instance and its state remains whole.
Within the lifecycle callback procedures, you can state how your activity behaves when the user exits and re-enters the activity. For instance, if you’re creating a streaming video player, you may pause the video and end the network connection when the user switches to a different app. When the user goes back, you can reconnect to the network and let the user resume the video from the same place.
Starting an Activity
Unlike other programming examples in which apps are launched with a main () method, the Android system starts code in an Activity example by invoking particular callback methods that matches the particular stages of its lifecycle. There is a succession of callback methods that initiates an activity and a succession of callback procedures that pull down an activity.
Comprehending the Lifecycle Callbacks
During the life of an activity, the system calls a central set of lifecycle procedures in a succession related to a step pyramid. That is, every stage of the activity lifecycle is a distinct step on the pyramid. As the system produces a fresh activity instance, each callback procedure moves the activity state one step toward the top. The top of the pyramid is the point at which the activity is running in the forefront and the user can relate to it.
As the user starts to exist the activity, the system calls other techniques that shift the activity state back down the pyramid so as to take to pieces the activity. In a few cases, the activity will shift only part way down the pyramid and wait for example when the user switches to a different app, from which location the activity can shift back to the top if the user goes back to the activity and start again where the user started off.
The figure above shows a basic design of the Activity lifecycle, articulated as a step pyramid.
This illustrates how, for every callback used to take the activity a step toward the Resumed state at the top, there’s a callback technique that takes the activity a step down. The activity can as well revisit the resumed state from the Paused and Stopped state.
Depending on the complexity of your activity, you probably don’t need to implement all the lifecycle methods. However, it’s important that you understand each one and implement those that ensure your app behaves the way users expect. Implementing your activity lifecycle techniques properly ensures your app behaves well in a lot of ways, including that it:
- Does not break down if the user receives a phone call or changes to another app while making use of the app.
- Does not consume valuable system resources when the user is not actively using it.
- Does not lose the user’s progress if they leave your app and return to it at a later time.
- Does not crash or lose the user’s progress when the screen rotates between landscape and portrait orientation.
There are a lot of situations in which an activity transitions between various states shown in the figure above but the static states among them are only three in number. That is, the activity can occur in one of only three states for an extensive period of time:
In the resumed state, the activity is in the forefront and the user can interact with it. This state is also known as the “running” state.
In the paused state, the activity is partly covered by another activity—the other activity that’s in the forefront is partly transparent or doesn’t envelop the whole screen. The paused activity does not accept user input and cannot create any code.
In the stopped state, the activity is entirely obscured and not seen by the user; it is taken to be in the backdrop. While stopped, the activity example and all its state information like member variables are preserved, but it cannot create any code.
The other states (Created and Started) are short-lived and the system speedily moves from them to the next state by calling the next lifecycle callback technique. That is, after the system calls onCreate(), it speedily calls onStart(), which is speedily followed by onResume().
Specify Your App’s Launcher Activity
When the user choose your app icon from the Home screen, the system calls the onCreate() method for the Activity in your app that you’ve specified to be the “launcher” (or “major”) activity. This is the activity that functions as the key entry point to your app’s user interface.
You can define which activity to use as the major activity in the Android manifest file, AndroidManifest.xml, which is at the root of your project directory.
The major activity for your app ought to be declared in the manifest with an <intent-filter> that includes the major action and launcher category.
Pausing and Resuming an Activity
During standard app use, the forefront activity is occasionally blocked by other visible components that make the activity topause. For instance, when a partially transparent activity opens like one in the style of a dialog, the earlier activity pauses. In so far as the activity is still partly visible but presently not the activity in focus, it continues to be in the paused state.
Nevertheless, once the activity is fully-obstructed and not visible, itstops
Pause Your Activity
When the system calls onPause() for your activity, it strictly means your activity is still partly visible, but most frequently is an indication that the user is exiting the activity and it will shortly enter the Stopped state. You ought to usually use the onPause() callback to:
- Terminate animations or other ongoing actions that could use up CPU.
- Commit unsaved changes, but only if users expect such changes to be enduringly saved when they exist for an instance a draft email.
- Release system resources, like broadcast receivers, handles to sensors (like GPS), or any resources that may affect battery life while your activity is on the paused state and the user does not require them.
For instance, if your application uses the Camera, the on Pause() technique is a good place to release it.
Resume Your Activity
When the user resumes your activity from the Paused state, the system calls the onResume() technique.
Know that the system calls this technique every time your activity comes into the forefront, including when it’s created for the first time. As such, you ought to implement onResume() to start off components that you release during onPause() and carry out any other initializations that must happen each time the activity enters the Resumed state like starting n animations and initializing components only used when the activity has user focus. The following example of onResume() is the counterpart to the onPause() example above, so it starts off the camera that’s released when the activity pauses.
Stopping and Restarting an Activity
Correctly stopping and restarting your activity is a crucial process in the activity lifecycle that ensures your users perceive that your app is always alive and doesn’t lose their progress. There are a few of key scenarios in which your activity is stopped and restarted:
- The user opens the Recent Apps window and switches from your app to a different app. The activity in your app that’s presently in the forefront is stopped. If the user returns to your app from the Home screen launcher icon or the Recent Apps window, the activity restarts.
- The user carries out an action in your app that starts a new activity. The present activity is stopped when the second activity is produced. If the user then presses the Backbutton, the first activity is restarted.
- The user receives a phone call while using your app on his or her phone.
The Activity class makes available two lifecycle techniques, onStop()and onRestart(), which let you to exclusively take care of how your activity manages being stopped and restarted. Unlike the paused state, which identifies a partly UI obstruction, the stopped state guarantees that the UI is no more visible and the user’s focus is in a distinct activity or a completely different app.
Understanding the Android lifecycle: How the Android application and activity life cycle works.
Managing the application life cycle
Android devices have restricted resources; thus the Android system is permitted to manage the existing resources by stopping running processes or recycling Android elements.
Together with resource management, Android as well recreates activities in case of any occurrence of a configuration change. The Configurationobject is composed of the present device configuration, if this configuration is changed; activities are restarted, because they may then use dissimilar resources for the new configuration.
For the user of the device this ought to occur plainly. This means that he should not note if an Android component have been ended nor not.
To maintain this, the Android platform carries lifecycle event which are mentioned in the case of process or component termination in addition to in the case of a configuration change. The developer takes charge of maintaining the status of the application. He is also in charge of restoring the activity instance state. The instance state of an activity is the non constant data that requires to be passed between activities restarts during a configuration alteration to restore user selections.
The application object is produced whenever one of your Android constituents is started. It is started in a fresh process with a unique ID under a single user. Even if you do not recognize one in your AndroidManifest.xml file, the Android system produces a default object for you. This object makes available a few main lifecycle methods:
- onCreate() – mentioned prior to the start of the first components of the application
- onLowMemory() – mentioned when the Android system makes a request that the application cleans up memory
- onTerminate() – This is merely used for testing, not mentioned in production
- onConfigurationChanged() – This is mentioned whenever the configuration changes
Application objects begins before any component and runs at least as long as another component of the application runs. If the Android system requires ending processes, it follows a few priority systems.
The Android system is as well permitted to recycle Android components to free up resources. This section explains which for activities, the lifecycle of other constituents is explained in the individual component of these constituents.
An activity can be in various states which are explained below:
Different Activity states
|Running||In this state, activity is visible and interacts with the user.|
|Paused||In this state, activity is still visible but partly masked; instance is running but may be killed by the system.|
|Stopped||In this state activity is not visible, instance is running but might be killed by the system.|
|Killed||In this state, activity has been terminated by the system by a call to its finish () method.|
The user ought not to observe if an activity which is still part of an activity pile has been ended or not. For this, the developer requires to store the state of the activity at the exact point in time and restore it. He ought to as well quit any pointless actions if the activity is not perceptible any longer to save system resources.
The Android system describes a lifecycle for activities through predefined (lifecycle) techniques. The most crucial techniques are:
Significant lifecycle techniques
|onCreate()||When this technique is called, the activity is created. It is used to start the activity, for instance produce the user interface.|
|onResume()||This is called if the activity become visible again and the user begin to interact with the activity again. It is used to start fields, index listeners, bind to services, etc.|
|onPause()||This is called immediately another activity comes into the forefront. It is always called prior to the time the activity is no longer visible again. This is used to free resources or save application data. For instance you unregister listeners, target receivers, liberate from services or get rid of system service listeners.|
|onStop()||This is called immediately the activity is no more visible. Time or CPU exhaustive shut-down operations, like writing information to a database ought to be down in the onStop() method. This technique is assured to be called as of API 11.|
Android has more life cycle techniques but not all of these techniques are guaranteed to be called. The onDestroy() technique is not guaranteed to be called, thus you characteristically don’t make use of it.
You can disregard the existing of the other lifecycle safe and sound. Applications are usually developed having other lifecycle techniques.
Instant State of an Activity
Instant state of an activity is required to restore the activity to the state in which the user left it.
Assume for example the user scrolled via a ListView with thousands of items and the activity is recreated. Losing the position in the list is annoying for the user, thus the position ought to be restored.
The onSaveInstanceState() can be used to store this instance state as a Bundle. A Bundle can contain primitive data types, arrays, String and objects which are of the Parcelable or Serialisable type.
The persisted Bundle data is passed at restart of the activity to the onCreate() method and onRestoreInstanceState() as parameter.
If you override onSaveInstanceState() and onRestoreInstanceState() you should call the super implementation of it, because the default views of Android store their data via a call to View.onSaveInstanceState from the onSaveInstanceState() method of the activity. For example EditText stores its content via the default call of this method.
The onRestoreInstanceState() or the onCreate() methods can be used to recreate the instance scope of an activity if it is restarted.
It is preferable to use the onRestoreInstanceState() method for restoring the instance state. This approach separates the initial setup from restoring the state.
If the user interacts with an activity and presses the Back button or if the finish() method of an activity is called, the activity is removed from the current activity stack and recycled. In this scenario, there is no instance state to save and the onSaveInstanceState() method is not called.
If the user interacts with an activity and presses the Home button, the activity instance state ought to be saved. The onSaveInstanceState() method is called. If the user restarts the application it will resume or restart the last running activity. If it restarts the activity it supplies the bundle with the save data to the onRestoreInstanceState() and onCreate() methods.
The onSaveInstanceState() method is not called if the user hits the back button. Don’t use this method to save the data which is required to get persisted.
Non Configuration instance scope
Non Configuration instance scope are Java objects which require to pass from one instance to the next instance of an activity in case of an configuration alteration.
Saving and restoring one object was possible with the getLastNonConfigurationInstance() and onRetainNonConfigurationInstance() methods. These methods have been denounced; you ought to preferably use headless retained fragments for holding to objects which ought to be passed between activity instances as a result of to configuration changes.
If you still make use of this method of the onRetainNonConfigurationInstance() method, make sure that you are not passing objects to the next instance which have a reference to the present instance of the activity, if not, you have produced a memory leak, i.e. the refuse collector cannot clear out the other instance of the activity since you are still holding on to a reference of it.