Topic 2: Understanding Lifecycles in deep

This is second topic of our learn android from basic to advance series

Topic 2: Understanding Lifecycles in deep

Hello devs, I Just wanted to give a quick update on our series - we've wrapped up our discussion on OOP concepts and now we're moving on to something equally important in Android development: lifecycles. Don't worry if you're new to this, we'll cover all the basics together. So, let's dive right into the topic!

Before moving on to the lifecycle let's discuss about the Android architecture.

Android Architecture

Android architecture is composed of several layers that work together to provide a robust platform for building mobile applications.

  1. Linux Kernel: At the core of Android is the Linux kernel, which provides basic system functionality such as process management, memory management, device drivers, and networking.

  2. Hardware Abstraction Layer (HAL): This layer abstracts the hardware-specific details, allowing the upper layers to interact with the hardware in a standardized way. It includes drivers for things like camera, Bluetooth, Wi-Fi, etc.

  3. Native Libraries: These are libraries written in C/C++ that provide core functionalities to the Android system. They include libraries like libc for standard C functions, SQLite for database management, and Surface Manager for handling display surfaces.

  4. Android Runtime (ART): ART is the runtime environment in which Android applications run. It's responsible for executing and managing application code written in Java/Kotlin or other supported languages. ART uses ahead-of-time (AOT) compilation for improved performance compared to the earlier Dalvik virtual machine.

  5. Java API Framework: This layer provides a set of Java libraries and APIs for building Android applications. It includes packages for activities, content providers, services, intents, and many others. Developers use these APIs to interact with various system components and build their applications.

  6. System Services: Android provides a set of system services that applications can use for common tasks such as managing network connectivity, accessing sensors, handling notifications, and more. These services are accessible via the Android framework and are managed by the system.

  7. Application Framework: This layer provides the building blocks for creating Android applications. It includes various managers (e.g., ActivityManager, WindowManager) responsible for managing application lifecycle, UI rendering, and interaction with system components.

  8. Applications: At the topmost layer are the applications themselves, which are the software programs developed by developers and installed on Android devices. These can be pre-installed system apps, bundled with the device's firmware, or downloaded from the Google Play Store or other sources.

Understanding the Android architecture is crucial for developers to build efficient and optimized applications that leverage the platform's capabilities effectively. It also helps in troubleshooting and optimizing performance issues.

Okay, devs now let's talk about the Android Lifecycle.

In Android development, two lifecycles occupy a significant place in our line of work. As developers, we are primarily concerned with these two lifecycles.

  • Activity Lifecycle

  • Fragment Lifecycle

Activity lifecycle

Every screen that is displayed on the mobile app is an activity with a set of states. The states of activity are responsible for the app's behaviour and user interaction.

  • onCreate()

  • onStart()

  • onResume()

  • onPause()

  • onRestart()

  • onStop()

  • onDestroy()

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

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

    override fun onStart() {
        super.onStart()
        println("Activity onStart")
    }

    override fun onResume() {
        super.onResume()
        println("Activity onResume")
    }

    override fun onPause() {
        super.onPause()
        println("Activity onPause")
    }

    override fun onStop() {
        super.onStop()
        println("Activity onStop")
    }

    override fun onDestroy() {
        super.onDestroy()
        println("Activity onDestroy")
    }
}

In this example, we've overridden each of the lifecycle methods and added a println() statement to indicate when each method is called. This will help you observe the lifecycle of the activity in the logcat output.

  • onCreate(): This method is called when an activity is first created. We can perform one-time initialisation for this method. Like setting up UI components or loading data.

  • onStart(): After onCreate(), this method was called. We can prepare our UI to be visible but cannot perform any heavy operation in this method.

  • onResume(): Whenever our app is visible and the user can interact with the app then this method is called. In this method, we can perform animation, play media and handle user interaction.

  • onPause(): If another activity comes into the foreground or the user presses the home button then this method is called. We pause ongoing operations and release resources here.

  • onRestart(): If an activity is stopped and then started again then this method was called before onStart().

  • onStop(): When an activity is no longer visible then this method is called. In this method, we can release resources that are no longer needed.

  • onDestroy(): When an activity is being destroyed then this method is called.

You can see the sequence of these methods being called as you interact with the activity, open other activities, or rotate the device (which might trigger configuration changes).

Fragment lifecycle

The fragment is used to display multiple views on a single Activity. The fragment's lifecycle is similar to the activity, with only a few additional states.

  • onAttach()

  • onCreate()

  • onCreateView()

  • onActivityCreated()

  • onStart()

  • onResume()

  • onPause()

  • onStop()

  • onDestroyView()

  • onDetach()

                  import android.os.Bundle
                  import android.util.Log
                  import android.view.LayoutInflater
                  import android.view.View
                  import android.view.ViewGroup
                  import androidx.fragment.app.Fragment
    
                  class MyFragment : Fragment() {
    
                      override fun onCreate(savedInstanceState: Bundle?) {
                          super.onCreate(savedInstanceState)
                          Log.d("Fragment Lifecycle", "onCreate")
                      }
    
                      override fun onCreateView(
                          inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?
                      ): View? {
                          Log.d("Fragment Lifecycle", "onCreateView")
                          // Inflate the layout for this fragment
                          return inflater.inflate(R.layout.fragment_my, container, false)
                      }
    
                      override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
                          super.onViewCreated(view, savedInstanceState)
                          Log.d("Fragment Lifecycle", "onViewCreated")
                      }
    
                      override fun onStart() {
                          super.onStart()
                          Log.d("Fragment Lifecycle", "onStart")
                      }
    
                      override fun onResume() {
                          super.onResume()
                          Log.d("Fragment Lifecycle", "onResume")
                      }
    
                      override fun onPause() {
                          super.onPause()
                          Log.d("Fragment Lifecycle", "onPause")
                      }
    
                      override fun onStop() {
                          super.onStop()
                          Log.d("Fragment Lifecycle", "onStop")
                      }
    
                      override fun onDestroyView() {
                          super.onDestroyView()
                          Log.d("Fragment Lifecycle", "onDestroyView")
                      }
    
                      override fun onDestroy() {
                          super.onDestroy()
                          Log.d("Fragment Lifecycle", "onDestroy")
                      }
    
                      override fun onDetach() {
                          super.onDetach()
                          Log.d("Fragment Lifecycle", "onDetach")
                      }
                  }
    

    In this example, we've overridden several lifecycle methods of the Fragment and added logging to each one to observe the fragment lifecycle in action.

    • onCreate(): Called to do the initial creation of the fragment.

    • onCreateView(): Called to create the view hierarchy associated with the fragment.

    • onViewCreated(): Called immediately after onCreateView() has returned, but before any saved state has been restored into the view.

    • onStart(): Called when the Fragment is visible to the user.

    • onResume(): Called when the Fragment is visible to the user and actively running.

    • onPause(): Called when the Fragment is no longer resumed.

    • onStop(): Called when the Fragment is no longer started.

    • onDestroyView(): Called when the view hierarchy associated with the fragment is being removed.

    • onDestroy(): Called when the fragment is no longer in use.

    • onDetach(): Called when the fragment is no longer attached to its activity.

By logging each method call, you can observe the sequence of fragment lifecycle events as the fragment is created, attached to an activity, displayed, and then destroyed or detached.

We've reached the end of this blog series, but don't worry, we'll be back with more exciting stuff on Android Components in our next blog. Can't wait to see you there!


Connect with Me:

Hey there! If you enjoyed reading this blog and found it informative, why not connect with me on LinkedIn? 😊 You can also follow my Instagram page for more mobile development-related content. πŸ“²πŸ‘¨β€πŸ’» Let’s stay connected, share knowledge and have some fun in the exciting world of app development! 🌟

Check out my Instagram page

Check out my LinkedIn

Β