0% found this document useful (0 votes)
21 views9 pages

Understanding Android Activity Lifecycle

Android
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views9 pages

Understanding Android Activity Lifecycle

Android
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Android Activity Lifecycle

● Android Activity Lifecycle is controlled by 7 methods of


[Link].
● Activity class. The android Activity is the subclass of
ContextThemeWrapper class.
● It is like a window or frame of Java.
● with the help of activity, you can place all your UI components or
widgets in a single screen.
● The 7 lifecycle method of Activity describes how activity will
behave at different states.
● To navigate transitions between stages of the activity lifecycle, the
Activity class provides a core set of six callbacks: onCreate(),
onStart(), onResume(), onPause(), onStop(), and onDestroy(). The
system invokes each of these callbacks as an activity enters a new
state.
1. onCreate(): In the onCreate() method, you perform basic
application startup logic that should happen only once for the
entire life of the activity.
● It is called when the activity is first created.
● This is where all the static work is done like creating views,
binding data to lists, etc.
● This method also provides a Bundle containing its previous
frozen state, if there was one.

public void onCreate(Bundle savedInstanceState) {


// call the super class onCreate to complete the creation of
activity like
// the view hierarchy
[Link](savedInstanceState); }

2. onStart() : The onStart() call makes the activity visible to


the user, as the app prepares for the activity to enter the
foreground and become interactive.
● It is invoked when the activity is visible to the user. It is
followed by onResume() if the activity is invoked from the
background.
● It is also invoked after onCreate() when the activity is first
started.
● The onStart() method completes very quickly and, as with the
Created state, the activity does not stay resident in the Started
state.
● Once this callback finishes, the activity enters the Resumed
state, and the system invokes the onResume() method.

protected void onStart()


{
// It will show a message on the screen
// then onStart is invoked
Toast toast = [Link](getApplicationContext(),
"onStart Called", Toast.LENGTH_LONG).show();
}

Toast means msg : Rushikesh is dancing shown to


user
The current situation is given by:
getApplicationContext()

3. onResume() : When the activity enters the Resumed state, it


comes to the foreground, and then the system invokes the
onResume() callback.
● This is the state in which the app interacts with the user. The app
stays in this state until something happens to take focus away from
the app.
● It is invoked when the activity starts interacting with the user.
● At this point, the activity is at the top of the activity stack, with a
user interacting with it.
● Always followed by onPause() when the activity goes into the
background or is closed by the user.

public class CameraComponent implements LifecycleObserver {

...

@OnLifecycleEvent([Link].ON_RESUME)
public void initializeCamera() {
if (camera == null) {
getCamera();
}
}

...
}

4. onRestart() : this method is invoked after the activity has


been stopped and prior to its starting stage and thus is always
followed by onStart() when any activity is revived from
background to on-screen.

protected void onRestart() {


// It will show a message on the screen
// then onRestart is invoked
Toast toast = [Link](getApplicationContext(),
"onRestart Called", Toast.LENGTH_LONG).show();
}

5. onPause() : The system calls this method as the first


indication that the user is leaving your activity.
● Use the onPause() method to pause or adjust operations
that should not continue while the Activity is in the
Paused state, and that you expect to resume shortly.
● There are several reasons why an activity may enter this
state.
● It is invoked when an activity is going into the
background but has not yet been killed. It is a
counterpart to onResume().
protected void onPause() {
// It will show a message on the screen
// then onPause is invoked
Toast toast =
[Link](getApplicationContext(), "onPause
Called", Toast.LENGTH_LONG).show();
}

6. onStop(): it has entered the Stopped state, and the system


invokes the onStop() callback.
● It is invoked when the activity is not visible to the user.
● It is followed by onRestart() when the activity is
revoked from the background, followed by onDestroy()
when the activity is closed or finished, and nothing
when the activity remains on the background only.
protected void onStop() {
// call the superclass method first
[Link]();

// save the note's current draft, because the activity is


stopping
// and we want to be sure the current note progress isn't
lost.
ContentValues values = new ContentValues();
[Link]([Link].COLUMN_NAME_NOTE,
getCurrentNoteText());
[Link]([Link].COLUMN_NAME_TITLE,
getCurrentNoteTitle());
}
7. onDestroy(): onDestroy() is called before the activity is
destroyed. The system invokes this callback either because:
● the activity is finishing (due to the user completely
dismissing the activity or due to finish() being called on the
activity), or
● the system is temporarily destroying the activity due to a
configuration change (such as device rotation or
multi-window mode)
● The final call received before the activity is destroyed. This
can happen either because the activity is finished (when
finish() is invoked) or because the system is temporarily
destroying this instance of the activity to save space.

protected void onDestroy() {


// It will show a message on the screen
// then onDestroy is invoked
Toast toast = [Link](getApplicationContext(),
"onDestroy Called", Toast.LENGTH_LONG).show();
}

The process

● When you open the app it will go through below states:

onCreate() –> onStart() –> onResume()

● When you press the back button and exit the app
onPaused() — > onStop() –> onDestroy()
● When you press the home button
onPaused() –> onStop()
● After pressing the home button, again when you open the app from a
recent task list
onRestart() –> onStart() –> onResume()
● After dismissing the dialog or back button from the dialog
onResume()
● If a phone is ringing and user is using the app
onPause() –> onResume()
● After the call ends
onResume()
● When your phone screen is off
onPaused() –> onStop()
● When your phone screen is turned back on
onRestart() –> onStart() –> onResume()

Java Program
package [Link]
import [Link]

//AppCompatActivity is the base class for activities with the support library action bar
features.

import [Link]
import [Link]
import [Link]
// Toast is the quick message for usesers
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
[Link](savedInstanceState)
setContentView([Link].activity_main)
print("***App state: OnCreate***n")
[Link](getApplicationContext(),"App state:
//getApplicationContext() Returns the context for all activities running in
application.
OnCreate",Toast.LENGTH_LONG).show();
}
override fun onStart() {
[Link]()
print("***App state: OnStart***n")
[Link](getApplicationContext(),"App state:
OnStart",Toast.LENGTH_LONG).show();
}
override fun onResume() {
[Link]()
print("***App state: OnResume***n")
[Link](getApplicationContext(),"App state:
OnResume",Toast.LENGTH_LONG).show();
}
override fun onStop() {
[Link]()
print("***App state: OnStop***n")
[Link](getApplicationContext(),"App state:
OnStop",Toast.LENGTH_LONG).show();
}
override fun onPause() {
[Link]()
print("***App state: OnPause***n")
[Link](getApplicationContext(),"App state:
OnPause",Toast.LENGTH_LONG).show();
}
override fun onRestart() {
[Link]()
print("***App state: OnReStart***n")
[Link](getApplicationContext(),"App state:
OnRestart",Toast.LENGTH_LONG).show();
}
override fun onDestroy() {
[Link]()
print("***App state: OnDestroy***n")
[Link](getApplicationContext(),"App state:
OnDestroy",Toast.LENGTH_LONG).show();
}
}

Common questions

Powered by AI

When an application is minimized using the home button, the activity lifecycle transitions through 'onPause()', 'onStop()', and remains in the stopped state. During 'onPause()', operations that should not continue in the background are halted, and in 'onStop()', resources not needed when the activity is not visible are relinquished. If the app is reopened from the recent tasks list, it transitions through 'onRestart()', 'onStart()', and 'onResume()', restoring interaction with the user and resources necessary to display the activity again .

The 'onResume()' method is invoked when the activity becomes the foreground activity, allowing it to interact with the user. In this state, the activity is at the top of the activity stack, and user interaction with it begins. The app remains in this state until an event occurs that takes the focus away, prompting a transition to 'onPause()'. It is crucial for activities that require user interaction, such as updating UI elements or restarting animations paused during the 'onPause()' state .

The 'onStart()' method is invoked following 'onRestart()' when an activity that has been stopped is being brought back to the foreground. This typically implies that the activity is transitioning from a non-visible state to a visible one, such as reopening the app from the recent apps list. In 'onStart()', activities initialize components that are required while the app maintains the visible state, preparing the app for the 'onResume()' state .

Within the 'onStop()' method, operations such as saving application data and freeing resources that are not needed unless the activity is visible should be performed. This callback is important because it is invoked when the activity is no longer visible to the user. Proper management within 'onStop()' can help ensure smooth app performance and improve resource utilization, given that the activity can be killed or reused after this method, depending on system resources. Saving the current state within 'onStop()' is crucial because the activity may be terminated without further notice if system resources are needed .

The 'onPause()' method is significant because it is the first indication that the user is leaving the activity. This method is used to pause or adjust operations that should not continue while the activity is in the paused state, such as stopping animations or saving state information. It may be called due to several reasons, such as when the user navigates to another activity or a system event occurs that partially obscures the application. It acts as a counterpart to 'onResume()', preparing the activity for an eventual transition to the 'paused' or 'stopped' states .

The 'onCreate()' method in the Android Activity lifecycle is responsible for critical application startup logic that is executed only once throughout the entire life of the activity. It is invoked when the activity is first created, where all the static setup is done, such as creating views, binding data to lists, etc. This method also takes a Bundle as an argument, containing the previous frozen state of the activity if there was one, which is pivotal for restoring the activity to its previous state. It is essential to call the superclass's 'onCreate()' method to complete the creation of the activity, like the view hierarchy .

Implementing a 'LifecycleObserver' benefits Android components like 'CameraComponent' by providing a structured way to observe lifecycle events and adjust component behavior accordingly. For instance, a 'CameraComponent' can automatically start accessing the camera when 'onResume()' is called and release the camera resource during 'onPause()', helping in optimizing resource use and preventing memory leaks. This approach adheres to best practices in managing lifecycle-aware components as it encapsulates state management logic within the components themselves, promoting modularity and reducing the risk of errors caused by manual lifecycle management .

The use of Toast messages in activity lifecycle methods can be helpful for debugging and understanding the lifecycle transitions as they provide visual confirmation of lifecycle method calls. However, a potential downside is that excessive use of Toast messages could lead to a cluttered user interface and may become a distraction, especially if they occur frequently or overlap during rapid lifecycle transitions. Additionally, they don't convey the message in a player-friendly way for the end-user interface in the production environment .

The 'onDestroy()' method enables developers to perform cleanup activities when an activity is finishing or being destroyed by the system. This could include finalizing resources such as closing database connections, unregistering broadcast receivers, and releasing resources that are not needed when the activity is no longer running. It is the final opportunity to clean up even those resources that are not critical to the existence of the activity itself, as 'onDestroy()' will not be called when the system decides to kill the process, so critical data should be saved in earlier callbacks like 'onStop()' .

The 'onRestart()' method is invoked when an activity that was previously stopped is being restarted before it transitions back to the 'started' state. It is always followed by 'onStart()'. This lifecycle callback allows developers to optimize the activity's state and resources, possibly reversing operations done during 'onStop()'. This is particularly useful when an activity is brought to the foreground again from a stopped state without being destroyed, such as when the app is reopened from the recent tasks list .

You might also like