Android Development

Practice And Learn Android Activity Lifecycle With Android Application

Understanding android activity lifecycle is essential for android development. Everyone who is learning android development needs to learn it first. Without learning android activity lifecycle, you will not be able to make a good android application nor you will be a good android developer.

Today, we will create an android application which will help us to easily understand android activity lifecycle. This android application will show you the name of each stage in which android activity enters. That live demonstration will make you understand android activity lifecycle in a good way. Here is the screenshot of the application.

Android activity lifecycle application countontechBefore creating android lifecycle application, take a look at below graph. It is showing you the lifecycle of an android activity.

 

Let’s create an android activity lifecycle application:

Start a new project in android studio and name it Android Lifecycle.

If you don’t know to create a project in android studio, consider to follow this post: Write Your First Android Application : “Hello World” of Android

Replace everything in activity_main.xml with following code.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <TextView
            android:id="@+id/text_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"/>

    </ScrollView>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="New Activity"/>

</LinearLayout>

In above code, we have created a TextView under ScrollView to show the stage of activity lifecycle and a Button to start a new activity.

Now, add a new activity in the project and name it SecondActivity. We are using two activity in this application to understand android activity lifecycle between two activities. To add new activity in project follow these steps.

Right click on app then point cursor to New >> Activity and select Empty Activity.

add new activity in android project countontech

Now name this new activity SecondActivity and click Finish.

add new activity countontech

Open activity_second.xml in editor and replace everything with following code.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <Button
        android:id="@+id/back_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Back" />

</LinearLayout>

In above code we have added a Button to go back to previous activity.

Now open SecondActivity.java in editor and replace everything (except first line which contains package com.example.androidlifecycle;) with below code.

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class SecondActivity extends AppCompatActivity {

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

        findViewById(R.id.back_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
}

Here in this code, we are setting an  OnClickListener to Button to call finish() when it press. It will stop Second activity and resume Main activity.

Now open MainActivity.java in editor and replace everything (except first line which contain package com.example.androidlifecycle;) with below code.

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    public StringBuilder stringBuilder = new StringBuilder();
    private String life;
    private TextView textView;
    private int counter = 0;

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

        textView = (TextView)findViewById(R.id.text_view);

        if (savedInstanceState != null){
            String saved_string = savedInstanceState.getString("savedString") + "\n";
            stringBuilder.append(saved_string);
            counter = savedInstanceState.getInt("counter");
        }

        counter++;
        life = counter+" - onCreate\n";
        stringBuilder.append(life);
        updateView();

        Button button = (Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    public void onStart(){
        super.onStart();
        counter++;
        life = counter +" - onStart\n";
        stringBuilder.append(life);
        updateView();
    }

    @Override
    public void onResume(){
        super.onResume();
        counter++;
        life = counter + " - onResume\n";
        stringBuilder.append(life);
        updateView();
    }

    @Override
    public void onPause(){
        super.onPause();
        counter++;
        life = counter + " - onPause\n";
        stringBuilder.append(life);
        updateView();
    }

    @Override
    public void onStop(){
        super.onStop();
        counter++;
        life = counter + " - onStop";
        stringBuilder.append(life+"\n");
        life = "onStop";
        Toast.makeText(this, life, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        counter++;
        life = "onDestroy";
        Toast.makeText(this, life, Toast.LENGTH_SHORT).show();
    }

    private void updateView(){
        textView.setText(stringBuilder);
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState){
        super.onSaveInstanceState(savedInstanceState);
        savedInstanceState.putString("savedString", stringBuilder.toString());
        savedInstanceState.putInt("counter", counter);
    }
}

In above code, we are creating a String with the name of stage in which activity entering and appending it to a StringBuilder then showing this StringBuilder in TextView. There is a Button to which we are setting OnClickListener to start Second activity when clicked.

We have created the app, Now just install it in your mobile or run it in emulator and view the android activity lifecycle in real time.

Here is the screenshot of the application. Thats all in this post.

Android activity lifecycle application countontech

Do you use Ubuntu and have been bored of default Ubuntu theme. Check this post : The Best Ubuntu Theme And Icon Pack To Make Ubuntu More Beautiful

If you like this post, don’t forget to share it with your friend. Thanks.

Nishant Bhakta

Hello this is Nishant Bhakta, The man behind this blog. I like writing blog, writing android code and watching movies. It's all i am getting about me for right now, when I get something more, it will be reflect here. Thanks
(Visited 176 times, 1 visits today)

10 thoughts on “Practice And Learn Android Activity Lifecycle With Android Application”

Leave a Reply

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