Skip to main content

Understanding the Life Cycle of a Activity

1. Using Android Studio , create a new Android project and name is Activity101.

2. In the Activity101Activity.java file , add the following highlighted statements.


Package com.example.activity101;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity
{
       String tag="LifeCycle Step";
      @Override
       protected void onCreate(Bundle savedInstanceState)
       {
               super.onCreate(savedInstanceState);
               setContentView(R.layout.activity_main);
               Log.d(tag,msg:"In the onCreate () event");
       }
       public void onStart()
       {
                super.onStart();
                Log.d(tag,msg:"In the onStart () event");
       }
       public void onRestart()
       {
                super.onRestart();
                Log.d(tag,msg:"In the onRestart () event");
       }
       public void onPause()
       {
                super.onPause();
                Log.d(tag,msg:"In the onPause () event");
       }
       public void onStop()
       {
                super.onStop();
                Log.d(tag,msg:"In the onStop () event");
       }
       public void onDestroy()
       {
                super.onDestroy();
                Log.d(tag,msg:"In the onDestroy () event");
       }
}

3. Press Shift + F9 to debug the application , or select Run -> Debug . Then select one of your Android Virtual Devices from the pop-up window.

4. When the activity is first loaded , you should see something very similar to the following in the logcat console . If you do not see the logcat console , click Android Monitor at the bottom of the Android Studio window:

11-16 06:25:59.369: D/Lifecycle step(559) : In the onCreate() event
11-16 06:25:59.369: D/Lifecycle step(559) : In the onStart() event
11-16 06:25:59.369: D/Lifecycle step(559) : In the onResume() event

5. If you click the Back button on the Android emulator , you see the following :

11-16 06:29:26.665: D/Lifecycle step(559) : In the onPause() event
11-16 06:29:28.465: D/Lifecycle step(559) : In the onStop() event
11-16 06:29:28.465: D/Lifecycle step(559) : In the onDestroy() event

6. Click the Home button , click the Overview icon , select the Android101 application , and observe the following :

11-16 06:25:59.369: D/Lifecycle step(559) : In the onCreate() event
11-16 06:25:59.369: D/Lifecycle step(559) : In the onStart() event
11-16 06:25:59.369: D/Lifecycle step(559) : In the onResume() event

7. Click the Home button and then click the Phone button on the Android emulator so that the activity is pushed to the background . Observe the output in the logcat window:

11-16 06:29:26.665: D/Lifecycle step(559) : In the onPause() event
11-16 06:29:28.465: D/Lifecycle step(559) : In the onStop() event

8. Notice that the onDestroy() event is not called , indicating that the activity is still in memory . Exit the phone dialer by clicking the Back button . The activity is now visible again. Observe the output in the logcat window :

11-16 06:29:28.465: D/Lifecycle step(559) : In the onRestart() event
11-16 06:29:28.465: D/Lifecycle step(559) : In the onStart() event
11-16 06:29:28.465: D/Lifecycle step(559) : In the onResume() event

The onRestart () event is now fired , following by the onStart() and onResume () methods.

How It Works 

As you can see from this simple example , an activity is destroyed when you click the Back button. This is crucial to understand because whatever state the activity is currently in will be lost . This means you need to write additional code in your activity to preserve its state when the activity is destroyed . At this point , note that the onPause ( ) method is called in both scenarios :
  • When an activity is send to the background
  • When a user kills an activity by tapping Back button
When an activity is started , the onStart() and onResume () methods are always called , regardless of whether the activity is restored from the background or newly created . When an activity is created for the first time , the onCreate () method is called .

From the preceding example , you can derive the following guidelines:
  • Use the onCreate() method to create and instantiate the objects that you will be using in your application.
  • Use the onResume() method to start any services or code that needs to run while your activity is in the foreground.
  • Use the onPause() method to stop any services or code that does not need to run when your activity is not in foreground.
  • Use the onDestroy() method to free up resources before your activity is destroyed.
NOTE Even of an application has only one activity and the activity is killed , the application is still running in memory.

Comments

Popular posts from this blog

Applying Styles and Themes to an Activity

By default , an activity is themed to the default Android theme. However , there been a push in recent year to adopt a new theme known as Material . The Material theme has a much more modern and clean look to it. There are two versions of the Material theme available to Android developers : Material Light and Material Dark , Either of these themes can be applied from the AndroidManifest.xml To apply one of the Material themes to an activity , simply modify the <Application> element in the AndroidManifest.xml file by changing the default android:theme attribute. (Please be sure to change all instances of "com.android" to whatever package name your project is using.) <?xml version="1.0" encoding="utf-8"?> <manifest xmls:android="http://schemas.android.com/apk/res/android"        xmlns:tools="http://schemas.android.com/tools"        package="com.android.activity101">        <application ...

Using Code Completion

Code completion is an invaluable tool that shows you contextual options for completing the piece of code that you are trying to write. For example, in the editor tab for the MainActivity.js file, locate the line that reads.          setContentView(R.layout.activity_main); Place your cursor after this line and press the Enter Key . On the new line , type the letter R , and then type a period, as shown here:          R. Android Studio Code Completion should display a list of values that you could use to try to complete the code statement. Figure shows what this list might look like . this is important if you are not entirely sure of the spelling of a method call or how to identify the different method signatures. NOTE if the code completion window does not open , press Ctrl + Space to force it to open. This is the same key combination used in some other IDEs for their versions of the code complet...

Now in Android

Android Studio 4.2 discharged to steady channel   Android Studio 4.2 is now available in the stable release channel. Read the blog for detailed information on what’s new, including a new tool to help migrate your project to the latest Android Gradle Plugin version. We’ve also enhanced lots of stuff such as Database Inspector , System Trace , SafeArgs support, Apply Changes, and the new project wizard. As always, download here and file issues here .           Hilt is stable and ready for production Manuel Vivo wrote about the stable release of Hilt , Android Jetpack’s recommended dependency injection (DI) solution for Android apps. Hilt is a simpler, more opinionated way to leverage the power of the Dagger DI library, eliminating boilerplate and reducing errors. It provides direct injection support for popular Jetpack libraries such as ViewModel, WorkManager, Navigation, and Compose. ( DI Basics , Documentation )   Google Play updates ...