Andrid Activity Lifecycle in kotlin

If you are learning Android app development in Kotlin, one of the first things you need to understand is the Activity Lifecycle. This lifecycle defines how your app behaves when the user opens, uses, or closes it.

In this blog post, I’ll explain it simply with code examples using Kotlin. Let’s go step-by-step!

What is an Activity in Android?

An Activity is a single screen in your app. For example, your home screen, app dashboard- all are Activities.

Android manages the Activities using something called the lifecycle

Activity Lifecycle Methods

There are 7 main lifecycle methods you should know:

Methods When is it called?
onCreate() When activity is first created
onStart() When the activity becomes visible to the user
onResume() When the user can intract with the screen
onPause() When the screen is partically hidden
onStop() When the screen is no longer visible
onRestart() When the user comes back to the Activity
onDestory() When the user can interact with the screen

Kotlin Code Example

package com.programmingkeeda.kotlindemo

import android.os.Bundle
import android.view.Gravity
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

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

override fun onStart() {
super.onStart()
showActivityLifeCycleState("onStart()")
}

override fun onResume() {
super.onResume()
showActivityLifeCycleState("onResume()")
}

override fun onPause() {
super.onPause()
showActivityLifeCycleState("onPause()")
}

override fun onDestroy() {
super.onDestroy()
// Avoid updating UI here
Toast.makeText(this, "onDestroy()", Toast.LENGTH_SHORT).show()
}

private fun showActivityLifeCycleState(state: String) {
val toast = Toast.makeText(this, state, Toast.LENGTH_SHORT)
toast.setGravity(Gravity.TOP or Gravity.CENTER_HORIZONTAL, 0, 200) // Try offsetting it

toast.show()
}
}

What You’ll See

When you open your app, you will see:

  • onCreate()

  • onStart()

  • onResume()

If you press the home button or go to another app:

  • onPause()

  • onStop()

If you reopen the app:

  • onRestart()

  • onStart()

  • onResume()

And when you close it completely:

  • onDestroy()

Β 

Β 

Show 1 Comment

1 Comment

  1. Vishal

    Great article, very informative and helpful. Thanks for sharing!

Leave a Reply

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