Activity Lifecycle in Android

Activity Lifecycle in Android

In Android Activity referred as an one screen in the application. The Activity in an application transition through different states in their lifecycle when user navigate through, out of and back to the application. The best example of video player application there can be multiple state when user play a video like play, resume, pause etc. The same thing exist for activity and there having a specific method for every single state and these are called Lifecycle Callback Method. Within the lifecycle callbacks methods, we can declare how activity will behaves when user leaves and re-enter to the activity. It is important to follow the all the steps of lifecycle to avoid memory leak or user data lose whenever application is closed for any reason or operating system decide to kill the application because lack of memory. Understanding the lifecycle is crucial for developing robust and responsive application.

Good implementation of the lifecycle callbacks can help your app to avoid the following problems:

  1. Crashing if user receive a phone call or switch to another app while using your app.

  2. Consuming valuable system resources when user is not actively using it.

  3. Crashing or losing user's progress when the screen rotates between landscape and portrait orientation.

  4. Losing the user's progress if they leave your app and return to it at a later time.

There are 7 methods that they have their own significance in each step in the lifecycle.

  1. onCreate()

  2. onStart()

  3. onResume()

  4. onPause()

  5. onStop()

  6. onRestart()

  7. onDestroy()

onCreate(): This method called when the activity is created for the first time. Perform basic application startup logic that happens only once for the entire life of the activity. This method is responsible for initializing the activity's UI such as inflating layout and finding views.

This method also provide a Bundles containing it's previous frozen states, if there was one. This means that in addition to saving the current state, the method also gives access to the any previously saved state, allowing developers to handle states transitions more effectively.

When an Android Activity is paused or stopped its state can be saved in a Bundle object. This Bundle contains key-value pairs representing the state of the activity, such as user input, scroll positions, or other data that needs to be preserved.

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
     companion object {
        // Keys for the data to be saved/restored
        private const val KEY_USER_INPUT = "user_input"
        private const val KEY_SCROLL_POSITION = "scroll_position"
    }
    private var userInput: String = ""
    private var scrollPosition: Int = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        Toast.makeText(this,"On Create",Toast.LENGTH_SHORT).show()
        val button = findViewById<Button>(R.id.btn_second)

        button.setOnClickListener {
            startActivity(Intent(this,SecondActivity::class.java))
        }
       findViewById<TextView>(R.id.textViewUserInput).text = userInput
       findViewById<ScrollView>(R.id.scrollView).scrollTo(0, scrollPosition)

        savedInstanceState?.let { bundle ->
            // Restore the state from the bundle
            userInput = bundle.getString(KEY_USER_INPUT, "")
            scrollPosition = bundle.getInt(KEY_SCROLL_POSITION, 0)
     }
   } 
  override fun onSaveInstanceState(outState: Bundle) {
        // Save the current state to the bundle
       outState.putString(KEY_USER_INPUT, userInput)
       outState.putInt(KEY_SCROLL_POSITION, scrollPosition)
       super.onSaveInstanceState(outState)
    }
    // This is just a mock method to simulate user input change
   private fun onUserInputChanged(newInput: String) {
       userInput = newInput
        // Update UI with the new input
        // For demonstration, assuming there's a TextView with id "textViewUserInput" to display user input
       findViewById<TextView>(R.id.textViewUserInput).text = userInput
    }

    // This is just a mock method to simulate scroll position change
   private fun onScrollPositionChanged(newPosition: Int) {
       scrollPosition = newPosition
   }

}
  • onCreate() method is called when the activity is created. Here, we check if there is a saved instance state (savedInstanceState). If it exists, we restore the state from the bundle.

  • onSaveInstanceState() method is called before the activity is destroyed. Here, we save the current state to the bundle.

  • We define keys (KEY_USER_INPUT and KEY_SCROLL_POSITION) to use when putting and getting data from the bundle.

  • We have two mock methods (onUserInputChanged() and onScrollPositionChanged()) to simulate changes in user input and scroll position. You can replace these methods with your actual methods that handle these changes in your application.

onStart() : This callback start when activity become visible to the user as the app prepare for the activity to enter the foreground and start interactive. It followed by onResume() if the activity invoke from background. Used this callback method to initialize code that maintain the UI likes start animation or attaching listener or receiver.

override fun onStart() {
    super.onStart()
    Toast.makeText(this,"On Start",Toast.LENGTH_SHORT).show()
}

onResume(): This callback start when user start interact with app. At this point, the activity is at the top of the activity stack. This is where you should register any listener or start any services that need to be running when activity is in the foreground. The app stays in this state until something happens to take focus away from the app, such as receiving a phone call, user navigate to another activity or the device screen turning off.

When an interruptive event occurs, system invoke onPause() callback and activity enter to the pause state. If the activity return to the resume state from pause state the system again invoke onResume() callback.

override fun onResume() {
    super.onResume()
    Toast.makeText(this,"On Resume",Toast.LENGTH_SHORT).show()

}

onPause(): It is invoke when an activity goin into the background but has not yet been killed. The opening of a new, semi-transparent activity, such as a dialog, pauses the activity it covers. So, it is recommended that heavy processing should not be done in this part. As long as the activity is partially visible but not in focus, it remains paused. It is good place to unregister any listeners, save any data that need to be saved and stop any services that don't need to be running in the background.

override fun onPause() {
    super.onResume()
    Toast.makeText(this,"On Pause",Toast.LENGTH_SHORT).show()

}

onStop(): This method is called when the activity is no longer visible to the user. This can occur when a newly launched activity covers the entire screen. It is a good place to stop animations and other visual changes. Note that this method may never be call in low memory situations where system doesn't have enough memory to keep the activity's process running after onPause() method is called.

override fun onStop() {
    super.onResume()
    Toast.makeText(this,"On Stop",Toast.LENGTH_SHORT).show()

}

onRestart(): The onRestart() method will be called whenever the Activity comes back from the invisible state. Suppose, we pressed the home button of the device and coming back, this onRestart() will be invoked.

override fun onRestart() {
    super.onResume()
    Toast.makeText(this,"On Restart",Toast.LENGTH_SHORT).show()

}

onDestroy(): This method is called when activity is about to destroy. This can happen either because the activity is finishing (when finish() is invoked) or because the system is temporarily destroy this instance of the activity to save space.

override fun onDestroy() {
    super.onResume()
    Toast.makeText(this,"On Destroy",Toast.LENGTH_SHORT).show()

}

My Sources:

1.https://developer.android.com/guide/components/activities/activity-lifecycle

2.https://www.geeksforgeeks.org/activity-lifecycle-in-android-with-demo-app/

3.https://medium.com/@ranjeet123/android-activity-lifecycle-in-detail-eaf2931a1b37

4.https://www.linkedin.com/pulse/activity-lifecycle-android-sagar-malhotra/