In this piece we will examine the lifecycle methods of an activity.
Example 1: Kotlin Android Activity Lifecycle
Examining in a practical manner the seven lifecycle methods of an activity. The app shows these lifecycle methods in a Toast message as well as logging them as they get raised.
Programming Language: Kotlin
Step 1: Create Project
Start by creating an empty Android Studio
project.
Step 2: Dependencies
No third party dependency is needed for this project.
Step 3: Design Layout
Design your User Interface for the app using XML as shown.
(a). activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity Life Cycle!"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Step 4: Write Code
(a). MainActivity.kt
Next Replace your MainActivity with the following code.
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
class MainActivity : AppCompatActivity() {
var TAG = "Event"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.d(TAG, "onCreate")
Toast.makeText(this,"onCreate",Toast.LENGTH_SHORT).show()
}
override fun onRestart() {
super.onRestart()
Log.d(TAG, "onRestart")
Toast.makeText(this,"onRestart",Toast.LENGTH_SHORT).show()
}
override fun onStart() {
super.onStart()
Log.d(TAG, "onStart")
Toast.makeText(this,"onStart",Toast.LENGTH_SHORT).show()
}
override fun onResume() {
super.onResume()
Log.d(TAG, "onResume")
Toast.makeText(this, "onResume", Toast.LENGTH_SHORT).show()
}
override fun onPause() {
super.onPause()
Log.d(TAG, "onPause")
Toast.makeText(this, "onPause", Toast.LENGTH_SHORT).show()
}
override fun onStop() {
super.onStop()
Log.d(TAG, "onStop")
Toast.makeText(this, "onStop", Toast.LENGTH_SHORT).show()
}
override fun onDestroy() {
super.onDestroy()
Log.d(TAG, "onDestroy")
Toast.makeText(this, "onDestroy", Toast.LENGTH_SHORT).show()
}
}
Run
Copy the code or download it in the link below, build and run.
Reference
Here are the reference links:
Number | Link |
---|---|
1. | Download Example |
2. | Follow code author |
Example 2: Log out Activity Lifecycle in Kotlin
A simple Kotlin Android Activity lifecycle tutorial.
Framework: AndroidX
Step 1: Create Project
The first step is to create a Android Project in Android Studio.
Step 2: Add Dependencies
No external dependencies are needed for this example.
Step 3: Design Layouts
Add a TextView inside a ConstraintLayout as follows:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.developers.activitylifecycle.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Step : Write Code
Our MainActivity
will simply log out the lifecycle methods in android:
MainActivity.java
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import java.util.logging.Logger
class MainActivity : AppCompatActivity() {
companion object {
val log = Logger.getLogger(MainActivity::class.java.name)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
log.info("OnCreate Called")
}
override fun onStart() {
super.onStart()
log.info("onStart Called")
}
override fun onRestart() {
super.onRestart()
log.info("OnRestart Called")
}
override fun onResume() {
super.onResume()
log.info("OnResume Called")
}
override fun onStop() {
super.onStop()
log.info("OnStop Called")
}
override fun onPause() {
super.onPause()
log.info("OnPause Called")
}
override fun onDestroy() {
super.onDestroy()
log.info("OnDestroy Called")
}
}
Run
Copy the code into your project or download the code in the reference links below.
Reference
Find the reference links below:
Number | Link |
---|---|
1. | Download code |
2. | Follow code author |
Example 3: Java Android Activity Lifecycle
This time round we will look at a simple lifecycle example in Java. The example will also log out the lifecycle states as the callbacks get raised.
Step 1: Create Project
The first step is to create a Android Project in Android Studio.
Step 2: Add Dependencies
Step 3: Design Layouts
Step : Write Code
Go to MainActivity.java
and add imports:
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
Extend the AppCompatActivity
:
public class MainActivity extends AppCompatActivity {
Override the onCreate():
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Inside it we will log out the following message:
LogData("onCreate Called");
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
And so on..
Here is the full code:
MainActivity.java
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LogData("onCreate Called");
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
@Override
protected void onStart() {
super.onStart();
LogData("onStart Called");
}
@Override
protected void onRestart() {
super.onRestart();
LogData("onRestart Called");
}
@Override
protected void onPause() {
super.onPause();
LogData("onPause Called");
}
@Override
protected void onResume() {
super.onResume();
LogData("onResume Called");
}
@Override
protected void onDestroy() {
super.onDestroy();
LogData("onDestroy Called");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
void LogData(String data) {
Toast.makeText(MainActivity.this, data, Toast.LENGTH_SHORT).show();
Log.d("TAG", data);
}
}
Run
Copy the code into your project or download the code in the reference links below.
Reference
Find the reference links below:
Number | Link |
---|---|
1. | Download code |
2. | Follow code author |