Activity Lifecycle in Android

Learn How To Manage The Activity Lifecycle in Android in Quick 25 Minutes

Introduction to Activity Lifecycle in Android

Android applications are very similar to Windows or Mac applications. They will have an interface. An interface may contain many screens. Out of which Activity is also a screen. Activity is similar to windows or Frame of Java. By using Activity class we can place the android components or UIs in a particular screen.

Detailed Concept of Activity

The Activity class may be a crucial segment of an Android app, and therefore the manner activities are propelled and assembled may be an essential a part of the platform’s application model. Not at all like programming ideal models where applications are launched with a main () method, the Android system initiates code in an Activity instance by invoking specific callback methods that correspond to specific stages of its lifecycle.

Just like any other language (other language starts with main ( ) function) android starts with onCreate( ) method on Activity is started.

The Activity class is meant to facilitate this paradigm. When one app invokes another, the calling app invokes an activity within the other app, instead of the app as an atomic whole. In this way, the activity is the entry point for an app’s interaction with the user. You implement an activity as a child class of the Activity class.

An Activity gives the graphical window during which the application draws its UI. This window regularly fills the screen, yet could likewise be smaller than the screen and floats on the head of different windows.

In general, one activity implements one screen in an app. For instance, one of an app’s activities may implement a Preferences screen, while another activity implements a select Photo screen.

Most apps contain different multiple screens, which suggests they comprise multiple activities. Typically, one activity in an app is specified because the main activity, which is that the first screen to seem when the user launches the app. Each activity can then start another activity to perform different actions. For example, the most activity during a simple e-mail app may provide the screen that shows an e-mail inbox. From there, most activity might launch other activities that provide screens for tasks like writing e-mails and opening individual e-mails.

Although activities work together to make a correspondent user experience in an app, each activity is just loosely sure to the opposite activities, there are usually minimal dependencies among the activities in an app. In fact, activities often begin activities belonging to other apps. For example, a browser app might launch the Share activity of a social-media app.

To use activities in your app, you want to register information about them within the app’s manifest, and you want to manage activity lifecycles appropriately.

Every activity navigates through various stage of the lifecycle. The activity and stages are governed by activity stacks. So, when a new activity starts, the previous activity is pushed to the activity stack and always stays below to it.

Declare activities

To declare your activity, open your manifest file and add a component as a toddler of the element. For example:  The only required attribute for this element is android: name, which specifies the category name of the activity. You can also add attributes that outline activity characteristics like label, icon, or UI theme.

Declare permissions

You can use the manifest’s <activity> tag to regulate which apps can start a specific activity. A parent activity cannot launch a child activity unless both activities have equivalent permission in their manifest. If you declare an element for a specific activity<uses-permission>for the parent, the child activity must have an identical element.

Concept of Intent

Intents are objects (type Message) which can request Android run time to start an activity. So all android activity is started and activate with the help of an Intent.

So whenever an app is getting launched from the home screen, it is powered by an intent provided by Android runtime. The android runtime actually sends the intent to the target app to start its main activity.

Apart from this intents are commonly used to send data from one activity to another. Intent class provides an intent object.

Types of intent

Intents can be primarily two types-

  1. Explicit intent- It works as a receiving activity by using activities fully qualified class name. (Example – Move within your own app).The components of Explicit intent are-
    1. The activity class
    2. The intent data
    3. Intent extra
    4. Intent Flags
  2. Implicit intent- It holds a general action that can be performed on the app. For Implicit intent, the app developer is responsible for providing intent action and category.

How to pass data between activities with the help of intents?

The steps are (for sending)-

  1. Generate an intent object
  2. Send data into the intent
  3. Start a new activity

(For receiving)- The steps are-

  1. Check for an activity starting point and tag the intent object.
  2. Retrieve the data from the intent object.

When do you need to use data over extra or extra over data?

The data that intent can hold is only one piece of information. The data can be represented as URI. In that scenario, developers need to use data over extra.

In case the developer wants to send multiple pieces of information and that information cannot be expressed as URI, developers need to use extra over data.

How to declare activities and intent filters

To announce your activity, open your manifest file, and add an element <activity> as a child of the element <application>.
For instance:


<manifest ... >
<application ... >
<activity android:name=".ExampleActivity" />
...
</application ... >
...
</manifest >

For this element, the only required attribute is android: name, which specifies the activity’s class name. You may also add attributes that describe characteristics of operation, such as the name, symbol, or theme for the UI. For more detail on these and other attributes, see the reference documentation for the feature < activity >.

 Intent filters are a very powerful Android platform feature. We offer the opportunity not only to initiate an operation based on an explicit request but also an implied one. For example, an explicit request may tell the system to “Begin the Send Email operation in the Gmail app.”

In comparison, an implicit request tells the system to “Begin a Send Email screen in any operation that can do the job.” If the system UI asks a user which application to use while performing a task, this is a purpose filter at work. You can exploit this function by declaring an attribute < intent-filter > in the element < activity >. The element description includes an element of < action >, and preferably an element of < category > and/or an element of < data >.

These elements combine to determine the type of purpose your operation should be able to react to. The following code snippet, for example, illustrates how to configure an operation that sends text data, and accepts requests from other activities for this:

<activity android:name=".ExampleActivity" android:icon="@drawable/app_icon">
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>

In this case, the element < action > specifies that data be sent from this operation. Declaring the element < category > as DEFAULT enables the operation to accept requests for initialization. The item < data > specifies the type of data this operation may send. The following code snippet illustrates how to name the aforementioned activity:

The java way of calling an activity:

// Create the text message with a string
Intent sendMessage = new Intent();
sendMessage.setAction(Intent.ACTION_SEND);
sendMessage.setType("text/plain");
sendMessage.putExtra(Intent.EXTRA_TEXT, textMessage);
// Start the activity
startActivity(sendMessage);

Any self-contained app or such an app that does not allow other apps to call its activities may ignore the intent filter.

The prime stags of activity

  1. Foreground activity-If an app stays on the foreground, the activity is known as active or running.
  2. A visible activity-In case the active app lost its focus and a non-full sized or transparent activity has got the focus. The activity is the alive state but cannot get back focus in current window mode.
  3. Background activity-In case any activity takes focus and the current activity goes behind or becomes hidden, the system may hold the information. But if further space is needed, the system may destroy the activity to reclaim the space.
  4. The empty process-The system may kill on activity by asking the user to finish or just by destroying it. When the activity is reopened, it restores its previous state.

The hierarchy of activity:

Hierarchy of Activity
Hierarchy of Activity

What is the need for an Activity?

The activity helps to keep the app safe while the below actions are performed-

  1. It protects any app if the user makes/ receive any call or switching to another app.
  2. It protects the system by consuming optimum resource and release the resources.
  3. It protects the user from losing track of their progress in the app.
  4. It also protects the user from losing track and their progress in case the user rotates the screen.

How to create Activity for an app?

  1. Open and create java class for activity.
  2. Write down code for the activity for GUI.
  3. Update manifest file for the new activity.

How to manage the activity lifecycle

The activity lifecycle consists of 7 methods. These methods are declared in android.app.Activity class. ContextThemeWrapper class is the parent class of the Activity class.

The operation covers a variety of states over the course of its lifespan. To handle the transitions between states, you use a series of callbacks. Such callbacks are added in the following pages.

 

MethodDescription
onCreatecalled when activity is first created.
onStartcalled when activity is becoming visible to the user.
onResumecalled when activity will start interacting with the user.
onPausecalled when activity is not visible to the user.
onStopcalled when activity is no longer visible to the user.
onRestartcalled after your activity is stopped, prior to start.
onDestroycalled before the activity is destroyed
Android-Activity-Lifecycle- Source java point
Android-Activity-Lifecycle- Source java point

The details of the methods

onCreate()

You have to implement the callback, which fires when your operation is generated by the program. The critical components of your operation should be initialized by your implementation.

So, this method is called when the activity is starting for the first time (creation time). In this method, all static tasks (like view creation, data bindings etc.) are done. This method can also access the data and state bundle from its previous frozen state. It is not killable

For example, your app will build views and connect data to the lists here. Most significantly, it is here that you need to call setContentView () to determine the user interface layout for the task.

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.widget.Toast; 
  
public class MyActivity extends AppCompatActivity { 
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    { 
        super.onCreate(savedInstanceState); 
        // Bundle is having previous frozen state 
  
        setContentView(R.layout.activity_main); 
        Toast toast = Toast.makeText( 
                       getApplicationContext(), 
                       "OnCreate is called", 
                       Toast.LENGTH_LONG) 
                  .show(); 
    } 
} 
OnStart()

If the app is in the foreground and it is visible to a user. This method kicks in. It can be involved after onResume(), if the activity is involved from background task or onCreate ( ) if it is running for the first time. It is not killable.

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.widget.Toast; 
  
public class MainActivity extends AppCompatActivity { 
  
    @Override
    protected void onCreate(Bundle savedInstanceState) 
   {
//oncreate method goes here
    } 
  
    protected void onStart() 
    { 
    Toast toast= Toast.makeText( 
                       getApplicationContext(), 
                       "Called onStart method", 
                       Toast.LENGTH_LONG) 
                  .show(); 
    } 
} 
onResume()

You must implement the callback, which will fire when the program generates your operation. Your implementation will initialize the critical components of your operation.

So, This method is called when the user starts interacting with the activity. During this phase, the activity belongs to the top of the activity stack. In case the user pushes it back, we need to talk onPause( ). It is not killable.

For example, your app should create views and link data to the lists here. Most importantly, you need to call setContentView here (to decide the layout of the user interface for the job.

  • When onCreate () finishes onStart is always the next callback.
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.widget.Toast; 
  
public class MainActivity extends AppCompatActivity { 
  
    @Override
    protected void onCreate(Bundle savedInstanceState) 
   {
//oncreate method goes here
    } 
  
    protected void onResume() 
    { 
  
        Toast toast = Toast.makeText( 
                       getApplicationContext(), 
                       "Called onResume method", 
                       Toast.LENGTH_LONG) 
                  .show(); 
    } 
} 
onPause()

If the operation loses concentration the program calls on Pause () (and enters a Paused state. For example, this state occurs when the user taps the Back or Recants button. If the program calls on Pause () for your task, this theoretically means that your task is still partially available, but most frequently it is an indicator that the user is leaving the activity and that the operation will soon reach the Stopped or Resumed state.

An operation in the State of Paused will continue to update the UI if the user intends to update the UI. Examples of such operation include one that displays a road chart screen or a replay from a video player. However, if these activities lose emphasis, the user expects a continuous updating of their UI.

You cannot save client or user data, make network calls, or perform database transactions with on Pause (). See Saving and Restore State of Operation for information on saving data.

When onPause () has finished executing the next callback is either onStop () or onResume (), depending on what happens after the operation has reached the state of Paused.

This method is called when the user pushes the application to the background but neither user nor the system kills it. It is just the opposite of onResume ( ). When the user switches to another activity that activity comes on the top of the screen, under the hood, this method is called the activity (new) can be completed until and unless the current activity’s onPause ( ) returns. This is the reason why onPause ( ) should not have any heavy tasks. It is killable in Build.VERSION – CODES.HONEYCOMB.

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.widget.Toast; 
  
public class MainActivity extends AppCompatActivity { 
  
    @Override
    protected void onCreate(Bundle savedInstanceState) 
   {
//oncreate method goes here
    } 
  
    protected void onPause() 
    { 
  Toast toast = Toast.makeText( 
                       getApplicationContext(), 
                       "Called onPause method", 
                       Toast.LENGTH_LONG) 
                  .show(); 
    } 
} 
onStop()

If the operation is no longer available to the user the program calls onStop (). It may happen because the activity is being demolished, a new activity is starting, or an established activity is entering a Resumed State and is covering the activity that has been halted. The stopped activity in all these cases is no longer visible at all.

The next callback the program calls is either onRestart (), (if the operation is returning to communicate with the user, or onDestroy () if this operation is terminating fully.

This method is called when an activity is no longer visible to the user. onRestart ( ) can be called if the user reinvoke the app from the background. onDestroy( ) can be called if the activity stays continuously in the background or the activity’s finished. Systems can also reclaim memory by destroying this activity. It is killable.

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.widget.Toast; 
  
public class MainActivity extends AppCompatActivity { 
  
    @Override
    protected void onCreate(Bundle savedInstanceState) 
   {
//oncreate method goes here
    } 
  
    protected void onStop() 
    { 
      Toast toast =Toast.makeText( 
                       getApplicationContext(), 
                       "Called onStop method", 
                       Toast.LENGTH_LONG) 
                  .show(); 
    } 
} 
onRestart()

This callback is triggered by the system when a Stopped State operation is about to restart. On Restart () restores the operation status from the time it was terminated.OnStart() also follows up on this callback.

This method is called when the user starts an activity that has been previously stopped. The activity moves back to foreground from background. It is not killable.

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.widget.Toast; 
  
public class MainActivity extends AppCompatActivity { 
  
    @Override
    protected void onCreate(Bundle savedInstanceState) 
   {
//oncreate method goes here
    } 
  
    protected void onRestart() 
    { 
  
        Toast toast 
            = Toast.makeText( 
                       getApplicationContext(), 
                       "Called onRestart method", 
                       Toast.LENGTH_LONG) 
                  .show(); 
    } 
} 
onDestroy()

Once an operation is lost, the device invokes this callback. The callback is the final one obtained by the operation. onDestroy () is generally implemented to ensure that all resources of operation are released when the operation or mechanism that comprises it is destroyed.

This method is called if the activity is completed or the system wants to reclaim the memory used by this activity. It is killable.

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.widget.Toast; 
  
public class MainActivity extends AppCompatActivity { 
  
    @Override
    protected void onCreate(Bundle savedInstanceState) 
   {
//oncreate method goes here
    } 
  
    protected void onDestroy() 
    { 
        Toast toast 
            = Toast.makeText( 
                       getApplicationContext(), 
                       "onDestroy Called", 
                       Toast.LENGTH_LONG) 
                  .show(); 
    } 
} 

This section merely introduces this subject. For a more detailed analysis of the life cycle of the operation and its callbacks, see The Lifecycle of Activities.

The sequence of Activities in different scenarios

Sequence of Activities
TaskActivities
Open an App onCreate() –> onStart() –>  onResume()
Press back button to exit the app onPaused() — > onStop() –> onDestory()
Home button pressonPaused() –> onStop()
Reopen the app from current tasks onRestart() –> onStart() –> onResume()
Dismiss a dialog onResume()
Phone rings when using the app onPause() –> onResume()
Call ends bring back the app onResume()
During screen offs automatically onPaused() –> onStop()
Screen on Restart() –> onStart() –> onResume()

Stating activity Code in Android Studio

Details of Android studio is given here.


public class MyActivity extends Activity {
...

static final int PICK_CONTACT_REQUEST = 0;

public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
// When the user center presses, let them pick a contact.
startActivityForResult(
new Intent(Intent.ACTION_PICK,new Uri("content://contacts")),
PICK_CONTACT_REQUEST);
return true;
}
return false;
}

protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == PICK_CONTACT_REQUEST) {
if (resultCode == RESULT_OK) {
// A contact was picked.  Here we will just display it
// to the user.
startActivity(new Intent(Intent.ACTION_VIEW, data));
}
}
}
}

This is a perfect example of Activity subclass called MyActivity, which overrides all of the above life cycle methods or functions:


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
    }
@Override
protected void onStart() {
super.onStart();
}

@Override
protected void onRestart() {
super.onRestart();
}

@Override
protected void onResume() {
super.onResume();
}

@Override
protected void onPause() {
super.onPause();
}

@Override
protected void onStop() {
super.onStop();
}

@Override
protected void onDestroy() {
super.onDestroy();
}
}

Output on your Mobile:

Activity Lifecycle- Output in Mobile
Activity Lifecycle- Output in Mobile

How to create an Activity?

Once you build a new Android project in Android Studio, the project will already contain a class of Android Activity (unless you chose not to build an activity).

Activity is at android.app. Activity subclass of the Android class. Here is an example of how a subclass of Activities may look:

package com.techtravelhub.myfirstandroidapp;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MyFirstAndroidActivity extends Activity {
}

This Subset of Operation does nothing important. It just extends the function of android.app.
The task subclass that Android Studio creates for you looks like this when you create a blank operation in Android Studio:

package com.techtravelhub.myfirstandroidapp;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;


public class MyFirstAndroidActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_first_android);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.my_first_android, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

How to Create an Activity in Android Studio?

Once you start a new project in Android Studio, you will be asked by the new project dialog if you want to start an operation in the project. When your software needs only one task a single screen, you do not need to build further subclasses of Task.

When your app requires more than one task, however, you can add a task to your project through the File menu, by selecting the menu item “Fresh ….” This is where the menu item is located

Activity Lifecycle- Create Activity in android studio
Activity Lifecycle- Create Activity in android studio

 

Click on the “Event” menu item in the menu that opens, and pick which type of activity you want to make. Here is how Android Studio looks like

Create blank activity
Create blank activity

Conclusion

This post talked about the activity lifecycle of an android application. I know this is the start and a primary guide for developing an application. Using this concept, you will be able to develop further. If this concept helps you in learning thanks me by sharing the post.

Further reading/References

Share and Enjoy !

Leave a Comment

Your email address will not be published. Required fields are marked *