0
0
Android Kotlinmobile~15 mins

Activity concept in Android Kotlin - Deep Dive

Choose your learning style9 modes available
Overview - Activity concept
What is it?
An Activity in Android is a single screen with a user interface. It acts like a page in an app where users can interact with buttons, text, images, and more. Each Activity controls what the user sees and how they can interact with it. When you open an app, you usually start with one Activity, and you can move to others as you use the app.
Why it matters
Activities organize the app into manageable screens, making it easier for users to navigate and for developers to build. Without Activities, apps would be confusing and hard to control because everything would happen on one screen. They help apps feel natural and responsive, like flipping pages in a book or moving between rooms in a house.
Where it fits
Before learning about Activities, you should understand basic Kotlin programming and how Android apps are structured. After mastering Activities, you can learn about Intents for moving between screens, Fragments for flexible UI parts, and the Android lifecycle to manage app behavior.
Mental Model
Core Idea
An Activity is like a single page in a book that shows content and handles user actions on that page.
Think of it like...
Think of an Activity as a room in a house where you do specific things. When you move to another room, you leave the current one and enter a new space with different furniture and tools.
┌───────────────┐
│   Activity    │
│ ┌───────────┐ │
│ │ UI Screen │ │
│ └───────────┘ │
│ User Actions │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Next Activity │
└───────────────┘
Build-Up - 7 Steps
1
FoundationWhat is an Activity in Android
🤔
Concept: Introduce the basic idea of an Activity as a screen in an app.
An Activity represents one screen in an Android app. It shows the user interface and responds to user input. When you open an app, the first screen you see is an Activity. You can have many Activities in one app, each showing different content.
Result
You understand that an Activity is the building block of app screens.
Knowing that Activities are the main way to show screens helps you organize app features clearly.
2
FoundationBasic Activity Structure in Kotlin
🤔
Concept: Learn how to create a simple Activity class in Kotlin.
In Kotlin, an Activity is a class that extends AppCompatActivity. It uses the onCreate() method to set up the screen. For example: class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
Result
You can write a minimal Activity that shows a layout on screen.
Understanding the onCreate() method is key because it sets up the screen when the Activity starts.
3
IntermediateActivity Lifecycle Basics
🤔Before reading on: do you think an Activity stays the same forever once opened, or does it change states? Commit to your answer.
Concept: Introduce the idea that Activities go through different states during their life.
An Activity doesn't just start and stay open. It moves through states like created, started, resumed (visible and interactive), paused (partly hidden), stopped (not visible), and destroyed. Android calls special methods like onStart(), onResume(), onPause(), and onDestroy() to let you handle these changes.
Result
You know that Activities have a lifecycle and can react to changes like the user leaving or returning.
Understanding lifecycle states helps you manage resources and keep the app responsive and efficient.
4
IntermediateNavigating Between Activities
🤔Before reading on: do you think Activities can open other Activities directly, or do they need a special message? Commit to your answer.
Concept: Learn how to move from one Activity to another using Intents.
To open a new Activity, you use an Intent, which is like a message saying 'start this screen.' For example: val intent = Intent(this, SecondActivity::class.java) startActivity(intent) This opens SecondActivity on top of the current one.
Result
You can switch screens in your app by starting new Activities.
Knowing how to navigate between Activities is essential for multi-screen apps and user flow.
5
IntermediatePassing Data Between Activities
🤔Before reading on: do you think Activities share data automatically, or do you have to send it explicitly? Commit to your answer.
Concept: Understand how to send information from one Activity to another using Intent extras.
You can attach extra data to an Intent before starting an Activity. For example: val intent = Intent(this, SecondActivity::class.java) intent.putExtra("username", "Alice") startActivity(intent) In SecondActivity, you retrieve it with: val username = intent.getStringExtra("username")
Result
You can pass simple data like text or numbers between screens.
Passing data explicitly keeps Activities independent and communication clear.
6
AdvancedHandling Activity Lifecycle for Data Safety
🤔Before reading on: do you think data in an Activity always stays safe when the screen rotates, or can it be lost? Commit to your answer.
Concept: Learn how to save and restore Activity state during lifecycle changes like rotation.
When the device rotates, the Activity is destroyed and recreated. To keep data safe, override onSaveInstanceState() to save data and restore it in onCreate(): override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString("key", value) } Then in onCreate(): val value = savedInstanceState?.getString("key")
Result
Your app keeps important data even when the screen changes orientation.
Managing state during lifecycle changes prevents frustrating data loss for users.
7
ExpertActivity Launch Modes and Task Management
🤔Before reading on: do you think every new Activity always creates a new instance, or can Android reuse existing ones? Commit to your answer.
Concept: Explore how Android controls Activity instances and tasks with launch modes like standard, singleTop, singleTask, and singleInstance.
Android can reuse or create new Activity instances based on launch modes set in the manifest or Intent flags. For example, singleTop reuses the Activity if it's already on top, avoiding duplicates. This controls how Activities stack and behave, affecting navigation and memory use.
Result
You can optimize app navigation and resource use by choosing the right launch mode.
Understanding launch modes helps prevent bugs like multiple copies of the same screen and improves user experience.
Under the Hood
An Activity is a Java/Kotlin class managed by the Android system. When started, Android creates an instance and calls lifecycle methods in a specific order. The system keeps Activities in a stack called the back stack, managing which one is visible. When the user navigates, Android pushes or pops Activities from this stack. The system also handles memory by destroying Activities when needed and recreating them later.
Why designed this way?
Android uses Activities and a back stack to mimic natural navigation, like pages in a book or screens in a phone. This design allows apps to manage multiple screens efficiently and lets users move back and forth easily. Alternatives like a single screen with many views would be harder to manage and less intuitive.
┌───────────────┐
│ Android OS    │
│  manages     │
│  Activity    │
│  lifecycle   │
└──────┬────────┘
       │
┌──────▼────────┐
│ Activity Stack│
│ (Back Stack)  │
│ ┌───────────┐│
│ │ Activity1 ││
│ │ Activity2 ││
│ │ Activity3 ││
│ └───────────┘│
└──────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think an Activity is always destroyed when you switch to another app? Commit yes or no.
Common Belief:An Activity is destroyed immediately when the user leaves it or switches apps.
Tap to reveal reality
Reality:Android may keep Activities in memory paused or stopped to allow quick return, destroying them only when resources are low.
Why it matters:Assuming Activities are always destroyed can lead to unnecessary data saving and restoring, hurting performance.
Quick: Do you think you can start an Activity without declaring it in the manifest? Commit yes or no.
Common Belief:You can start any Activity class without registering it in the AndroidManifest.xml file.
Tap to reveal reality
Reality:Every Activity must be declared in the manifest; otherwise, the app will crash when trying to start it.
Why it matters:Missing manifest declarations cause runtime crashes that confuse beginners.
Quick: Do you think the onCreate() method is called every time the Activity becomes visible? Commit yes or no.
Common Belief:onCreate() runs every time the Activity appears on screen.
Tap to reveal reality
Reality:onCreate() runs only once when the Activity is first created; other methods like onStart() and onResume() run when it becomes visible again.
Why it matters:Misunderstanding this leads to inefficient code and bugs when initializing UI or data multiple times.
Quick: Do you think Intents automatically share data between Activities without extra code? Commit yes or no.
Common Belief:Starting an Activity automatically shares all data between the current and new Activity.
Tap to reveal reality
Reality:Data must be explicitly passed using Intent extras; otherwise, Activities have no shared data.
Why it matters:Assuming automatic data sharing causes bugs where screens show empty or wrong information.
Expert Zone
1
Activities can be recreated by the system at any time, so relying on instance variables without saving state leads to data loss.
2
Launch modes and Intent flags interact in complex ways; understanding their combination is key to controlling navigation stacks precisely.
3
Using Fragments inside Activities can improve UI flexibility but requires careful lifecycle management to avoid leaks and crashes.
When NOT to use
Avoid using multiple Activities for very small UI changes; instead, use Fragments or Compose screens for better performance and simpler navigation. Also, for background tasks or no UI, use Services or WorkManager instead of Activities.
Production Patterns
In real apps, Activities often serve as containers for Fragments, handling navigation and lifecycle, while UI logic lives in Fragments. Developers use launch modes to prevent duplicate screens and manage deep links. State saving is carefully implemented to handle configuration changes and process death.
Connections
Fragment concept
Builds-on
Fragments are like mini-Activities inside an Activity, allowing more flexible and reusable UI parts within a single screen.
Intent messaging
Same pattern
Intents are the communication method between Activities, similar to sending letters between rooms in a house to coordinate actions.
Web page navigation
Analogy across domains
Navigating between Activities is like clicking links between web pages, each with its own content and back button behavior.
Common Pitfalls
#1Losing user data on screen rotation
Wrong approach:class MainActivity : AppCompatActivity() { var count = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
Correct approach:class MainActivity : AppCompatActivity() { var count = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) count = savedInstanceState?.getInt("count") ?: 0 } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putInt("count", count) } }
Root cause:Not saving and restoring state causes data loss when the Activity is recreated.
#2Starting Activity not declared in manifest
Wrong approach:val intent = Intent(this, HiddenActivity::class.java) startActivity(intent) // HiddenActivity not in manifest
Correct approach:Declare HiddenActivity in AndroidManifest.xml: Then start it as above.
Root cause:Forgetting to register Activities causes runtime crashes.
#3Assuming onCreate runs every time Activity appears
Wrong approach:override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Refresh UI every time Activity is visible here }
Correct approach:Use onStart() or onResume() to refresh UI when Activity becomes visible: override fun onResume() { super.onResume() // Refresh UI here }
Root cause:Misunderstanding lifecycle method purposes leads to inefficient or buggy UI updates.
Key Takeaways
An Activity is a single screen in an Android app that manages the user interface and user interactions.
Activities have a lifecycle with states like created, started, resumed, paused, and destroyed, which you must handle to keep apps responsive and data safe.
You navigate between Activities using Intents, which can also carry data explicitly between screens.
Properly saving and restoring Activity state prevents data loss during configuration changes like screen rotation.
Advanced control of Activities involves launch modes and task management to optimize navigation and resource use.