Activities & Intents

Lifecycle, explicit & implicit intents, data passing, and intent filters

Lifecycle Explicit Intent Implicit Intent Intent Filters

Table of Contents

1Activity Lifecycle (Detailed)

An Activity is a single, focused screen that users interact with. Android manages activities through a lifecycle — a series of callback methods triggered as the activity enters, exits, or returns to the foreground.

Why does lifecycle matter?

  • Save user data before the app is killed
  • Release resources (camera, sensors) when not needed
  • Handle interruptions (phone calls, screen rotation, app switching)

The 7 Lifecycle Callbacks (in order)

[App launched] ↓ onCreate() ← Activity is being created (set layout here) ↓ onStart() ← Activity becomes visible (but not interactive yet) ↓ onResume() ← Activity is in foreground & user can interact ↓ [User presses Home / Receives call / Another activity opens] ↓ onPause() ← Activity partially visible (stop animations, release heavy resources) ↓ onStop() ← Activity no longer visible ↓ [User returns to activity] ↓ onRestart() ← Called only if activity was stopped (not destroyed) ↓ onStart() ↓ onResume() ↓ [System kills activity to free memory (rare)] ↓ onDestroy() ← Final call before activity is destroyed

Visual Diagram with State Transitions

┌─────────────────────────────────────────┐ │ │ ↓ │ ┌─────────┐ │ │ onCreate│ │ └────┬────┘ │ ↓ │ ┌─────────┐ ┌───────────┐ ┌──────────┴─────┐ │ onStart │────→│ onRestart │←────│ onStop │ └────┬────┘ └───────────┘ └───────┬───────┘ ↓ ↑ ┌─────────┐ ┌─────────┐ │ │ onResume│ │ onPause │──────────────┘ └────┬────┘ └────┬────┘ │ │ [User interacts] │ │ │ (another activity opens) ↓ ↓ ┌─────────┐ ┌──────────┐ │ onPause │────→│ onStop │ └─────────┘ └──────────┘ │ (system kills) ↓ ┌──────────┐ │onDestroy │ └──────────┘

Understanding Each Method

MethodWhen CalledWhat to Do HereCan it be skipped?
onCreate()First time activity is createdInitialize UI (setContentView), bind data, set up click listenersNo
onStart()Activity becomes visibleRegister sensors, start UI updates (e.g., location)Sometimes (if resumed directly)
onResume()Activity is in foreground and interactiveStart animations, acquire camera, start video playbackNo
onPause()Activity loses focus (still partially visible)Pause animations, release camera, save unsaved changesYes (rarely)
onStop()Activity is no longer visibleStop heavy tasks, unregister receivers, save persistent dataYes
onRestart()Activity restarts after being stoppedUsually empty – prepare for restartYes
onDestroy()Activity is being destroyedClean up global resources, dismiss dialogsYes (if system kills process)

Code Example: Logging Lifecycle (Add to MainActivity.kt)

Kotlin — MainActivity.ktclass MainActivity : AppCompatActivity() { private val TAG = "Lifecycle" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) Log.d(TAG, "onCreate called") } override fun onStart() { super.onStart() Log.d(TAG, "onStart called") } override fun onResume() { super.onResume() Log.d(TAG, "onResume called") } override fun onPause() { super.onPause() Log.d(TAG, "onPause called") } override fun onStop() { super.onStop() Log.d(TAG, "onStop called") } override fun onRestart() { super.onRestart() Log.d(TAG, "onRestart called") } override fun onDestroy() { super.onDestroy() Log.d(TAG, "onDestroy called") } }
Test it

Run the app, press Home, press Recent Apps and return, rotate the screen, press Back. Watch Logcat (View → Tool Windows → Logcat) to see the sequence.

Special Case: Screen Rotation

When you rotate the device, Android destroys and recreates the activity:

onPause() → onStop() → onDestroy() → onCreate() → onStart() → onResume()

This is why you need onSaveInstanceState() to preserve data across rotations.

Saving State with onSaveInstanceState()

Kotlin — Save and restore stateoverride fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString("user_name", "Alice") outState.putInt("score", 42) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) if (savedInstanceState != null) { val userName = savedInstanceState.getString("user_name") val score = savedInstanceState.getInt("score") Log.d(TAG, "Restored: $userName, score $score") } }

Lifecycle Cheat Sheet for Common Scenarios

ScenarioCallback Sequence
Launch apponCreate → onStart → onResume
Press Home buttononPause → onStop
Return to app from HomeonRestart → onStart → onResume
Open another activity (full screen)onPause → onStop (current activity)
Back to first activityonRestart → onStart → onResume
Press Back buttononPause → onStop → onDestroy
Rotate screenonPause → onStop → onDestroy → onCreate → onStart → onResume
Low memory kills background activityonPause → onStop → onDestroy (without onSaveInstanceState)

2Activity Methods (Beyond Lifecycle)

Activities have many useful methods beyond lifecycle callbacks:

MethodPurposeExample
setContentView()Set layout XMLsetContentView(R.layout.activity_main)
findViewById()Get view by ID (Kotlin: use view binding)findViewById<TextView>(R.id.title)
finish()Close the activityfinish() (returns to previous screen)
startActivity()Start a new activitystartActivity(intent)
startActivityForResult()Deprecated — use ActivityResultLauncherSee modern API below
getIntent()Get the Intent that started this activityval intent = intent
setResult()Return result to previous activitysetResult(RESULT_OK, dataIntent)
onBackPressed()Handle back button pressOverride for custom behavior
moveTaskToBack()Send app to background (like Home button)moveTaskToBack(true)

Modern API: registerForActivityResult() (replaces startActivityForResult)

Kotlin — Activity Result API// In MainActivity private val getResultLauncher = registerForActivityResult( ActivityResultContracts.StartActivityForResult() ) { result -> if (result.resultCode == RESULT_OK) { val data = result.data?.getStringExtra("returned_data") Toast.makeText(this, "Returned: $data", Toast.LENGTH_SHORT).show() } } // Later, launch the activity val intent = Intent(this, SecondActivity::class.java) getResultLauncher.launch(intent)

3Explicit Intent

An explicit intent specifies exactly which component (activity, service, receiver) to start by name. Use it when you know the target class.

Syntax

Kotlinval intent = Intent(this, TargetActivity::class.java) startActivity(intent)

Complete Example: MainActivity → SecondActivity

1

Create SecondActivity: Right-click com.example.myfirstapp → New → Activity → Empty Views Activity. Name: SecondActivity. Android Studio adds it to the manifest automatically.

2

Add button in activity_main.xml with id goToSecondButton.

3

Implement click in MainActivity.kt (see code below).

XML — activity_main.xml<Button android:id="@+id/goToSecondButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Go to Second Activity" />
Kotlin — MainActivity.ktclass MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val button = findViewById<Button>(R.id.goToSecondButton) button.setOnClickListener { // Explicit Intent val intent = Intent(this, SecondActivity::class.java) startActivity(intent) } } }

Passing Simple Data with Explicit Intent

Kotlin — Send and receive extras// Sending (MainActivity) val intent = Intent(this, SecondActivity::class.java).apply { putExtra("USER_NAME", "Alice") putExtra("USER_AGE", 25) putExtra("IS_PREMIUM", true) } startActivity(intent) // Receiving (SecondActivity) val userName = intent.getStringExtra("USER_NAME") ?: "Guest" val userAge = intent.getIntExtra("USER_AGE", 0) val isPremium = intent.getBooleanExtra("IS_PREMIUM", false) textView.text = "Hello $userName, Age: $userAge, Premium: $isPremium"

Passing Serializable / Parcelable Objects

Kotlin — Parcelable User object// Data class (use @Parcelable for better performance) @Parcelize data class User(val name: String, val age: Int) : Parcelable // Sending val user = User("Bob", 30) intent.putExtra("USER_OBJ", user) // Receiving val user = if (Build.VERSION.SDK_INT >= 33) { intent.getParcelableExtra("USER_OBJ", User::class.java) } else { @Suppress("DEPRECATION") intent.getParcelableExtra("USER_OBJ") }

4Implicit Intent

An implicit intent doesn't specify the component name. Instead, it declares an action and optionally a data URI. Android finds the best app that can handle that action (browser, camera, dialer, share sheet).

ActionPurposeExample Code
ACTION_VIEWView a URI (web, map, phone)Intent(Intent.ACTION_VIEW, Uri.parse("https://google.com"))
ACTION_DIALOpen dialer with numberIntent(Intent.ACTION_DIAL, Uri.parse("tel:123456789"))
ACTION_CALLDirect call (needs permission)Intent(Intent.ACTION_CALL, Uri.parse("tel:123456789"))
ACTION_SENDShare text/contentIntent(Intent.ACTION_SEND).putExtra(...)
ACTION_SENDTOSend SMSIntent(Intent.ACTION_SENDTO, Uri.parse("smsto:12345"))
ACTION_PICKPick contact/photoIntent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI)
ACTION_IMAGE_CAPTUREOpen cameraIntent(MediaStore.ACTION_IMAGE_CAPTURE)

Example 1: Open a Webpage

Kotlinval webIntent = Intent(Intent.ACTION_VIEW, Uri.parse("https://developer.android.com")) startActivity(webIntent)

Example 2: Make a Phone Call

Kotlinval dialIntent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:9876543210")) startActivity(dialIntent) // Opens dialer, doesn't call directly

Example 3: Share Text (Using ShareSheet)

Kotlinval shareIntent = Intent(Intent.ACTION_SEND).apply { type = "text/plain" putExtra(Intent.EXTRA_TEXT, "Check out this amazing app!") putExtra(Intent.EXTRA_SUBJECT, "Sharing something cool") } startActivity(Intent.createChooser(shareIntent, "Share via"))

Example 4: Open a Location in Google Maps

Kotlinval gmmIntent = Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=Times Square, New York")) startActivity(gmmIntent)

Example 5: Capture a Photo (Implicit + Result)

Kotlinprivate lateinit var photoUri: Uri private val takePictureLauncher = registerForActivityResult( ActivityResultContracts.TakePicture() ) { success -> if (success) { imageView.setImageURI(photoUri) } } fun capturePhoto() { val photoFile = File(getExternalFilesDir(null), "photo.jpg") photoUri = FileProvider.getUriForFile( this, "${packageName}.fileprovider", photoFile ) takePictureLauncher.launch(photoUri) }

What if no app can handle the implicit intent?

Calling startActivity() with an intent that has no matching app causes a crash. Always check:

Kotlin — Safe implicit intent launchval intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://google.com")) if (intent.resolveActivity(packageManager) != null) { startActivity(intent) } else { Toast.makeText(this, "No app can handle this", Toast.LENGTH_SHORT).show() }

5Passing Data Between Activities (Advanced)

Method 1: Using putExtra() (simple types)

Covered in Explicit Intent section — works for primitives and Strings.

Method 2: Using Bundles (organized data)

Kotlin — Bundle extras// Sender val bundle = Bundle().apply { putString("name", "Charlie") putInt("score", 100) putStringArray("tags", arrayOf("gamer", "coder")) } val intent = Intent(this, SecondActivity::class.java).putExtras(bundle) startActivity(intent) // Receiver val bundle = intent.extras ?: Bundle() val name = bundle.getString("name")

Method 3: Passing data BACK to previous activity

MainActivity (caller):

Kotlin — MainActivity callerprivate val getResultLauncher = registerForActivityResult( ActivityResultContracts.StartActivityForResult() ) { result -> if (result.resultCode == RESULT_OK) { val returnedText = result.data?.getStringExtra("result_data") ?: "" textViewResult.text = returnedText } } fun openSecondForResult() { val intent = Intent(this, SecondActivity::class.java) getResultLauncher.launch(intent) }

SecondActivity (callee):

Kotlin — SecondActivity calleefun sendResultBack() { val resultIntent = Intent().apply { putExtra("result_data", "Hello from Second Activity!") } setResult(RESULT_OK, resultIntent) finish() // Closes activity and returns to MainActivity }

Method 4: Using ViewModel (shared across activities — advanced)

For complex data sharing, use a shared ViewModel scoped to the application or use SharedPreferences/database.

6Intent Filters

An intent filter (declared in the manifest) tells Android what implicit intents an activity can handle. Without intent filters, an activity can only be started via explicit intent.

Manifest Example: Making an Activity Handle "VIEW" Actions

XML — AndroidManifest.xml<activity android:name=".MyWebViewerActivity"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="https" /> <data android:host="*.google.com" /> </intent-filter> </activity>

Now when any app tries to open a https://maps.google.com URL, your activity appears in the chooser.

Anatomy of an Intent Filter

ElementDescriptionExample
<action>What the activity can doandroid.intent.action.VIEW, android.intent.action.SEND
<category>Context of the actionDEFAULT (required for implicit intents), BROWSABLE (safe for browser)
<data>Type of data acceptedandroid:scheme="https", android:mimeType="image/*"

Custom URL scheme (myapp://open)

XML — Custom deep link<intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="myapp" android:host="open" /> </intent-filter>

Now myapp://open opens your activity.

Handling text share

XML — Receive shared text<intent-filter> <action android:name="android.intent.action.SEND" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="text/plain" /> </intent-filter>

Getting data from the intent that started your activity

Kotlin — MyWebViewerActivityclass MyWebViewerActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_web_viewer) val action = intent.action val data = intent.data // URI that triggered this if (Intent.ACTION_VIEW == action && data != null) { webView.loadUrl(data.toString()) } } }

Comparison: Explicit vs Implicit Intents

AspectExplicit IntentImplicit Intent
TargetSpecific class nameAny app that can handle action
Use caseNavigating within your appUsing external apps (browser, camera, share)
RequiresClass referenceAction and data
Manifest declarationAlways requiredNot required for calling; required for receiving
ExampleIntent(this, Settings::class.java)Intent(ACTION_VIEW, webUri)
Who handles itExactly your componentSystem resolves best match

7Hands-On Exercises

1

Create a two-activity app where MainActivity has an EditText and a button. Clicking the button sends the text to SecondActivity and displays it there.

2

Use an implicit intent to open a specific location in Google Maps (e.g., Eiffel Tower).

3

Implement data return: In SecondActivity, add a button that sends a message back to MainActivity and displays it in a TextView.

4

Create a share button that shares a text message (e.g., "I love learning Android!") using ACTION_SEND.

5

Add an intent filter to one of your activities so it can be opened via a custom scheme myapp://start.

6

Experiment with lifecycle: Add Log statements to all lifecycle methods, then rotate the screen, press Home, open another app, and return. Observe the sequence in Logcat.

8Common Errors & Solutions

ErrorCauseFix
ActivityNotFoundExceptionActivity not declared in manifestAdd <activity> tag for explicit; check action for implicit
NullPointerException on intent.getStringExtra()Extra key doesn't existUse default values: intent.getStringExtra("key") ?: ""
App crashes when opening implicit intentNo app can handle the intentCheck resolveActivity() before calling
Data lost on screen rotationNot saving stateImplement onSaveInstanceState()
Can't pass custom objectObject not ParcelableAdd @Parcelize or implement Parcelable manually

9Summary Cheatsheet

Activity Lifecycle Methods (in order): onCreate() → onStart() → onResume() → (running) → onPause() → onStop() → onDestroy() Explicit Intent: Intent(this, TargetActivity::class.java).apply { putExtra("key", value) } Implicit Intent: Intent(Intent.ACTION_VIEW, Uri.parse("https://google.com")) Receiving Data: val value = intent.getStringExtra("key") Returning Data: setResult(RESULT_OK, Intent().putExtra("key", value)) finish() Intent Filter in Manifest: <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <data android:scheme="https" /> </intent-filter>

Activities & Intents MCQ Practice

10 Basic MCQs 10 Advanced MCQs

10 Basic Activities & Intents MCQs

1

First lifecycle callback when Activity appears?

AonCreate()
BonDestroy()
ConStop()
DonPause()
Explanation: onCreate initializes UI and state when Activity is first created.
2

onResume() means Activity is?

AVisible and interactive
BDestroyed
COnly created
DBackground forever
Explanation: onResume: foreground, user can interact.
3

Explicit Intent specifies?

AExact component class to launch
BOnly MIME type
CRandom action
DNo target
Explanation: Explicit intents set component/class for in-app navigation.
4

Implicit Intent specifies?

AAction (and optional data) resolved by system
BExact package only
CGradle task
DLayout ID
Explanation: System picks Activity matching intent-filter (e.g., VIEW http URL).
5

Pass small data between Activities via?

AIntent extras (Bundle)
BSharedPreferences only
CNew process
DManifest
Explanation: putExtra/getExtra on Intent for primitives, strings, Parcelables.
6

onPause() is called when?

AActivity losing focus partially
BApp installed
CGradle sync
DFirst boot only
Explanation: Another Activity partially covers the screen or a dialog appears — pause heavy work.
7

startActivity() requires?

AIntent
BSQL query
CDrawable
DService binding
Explanation: You pass an Intent to launch another Activity.
8

LAUNCHER category with MAIN action?

AEntry icon in app drawer
BSecret debug mode
CContent provider
DWallpaper
Explanation: Standard launcher Activity registration.
9

onDestroy() indicates?

AFinal cleanup before Activity removal
BApp always exits OS
CLayout inflation
DIntent filter match
Explanation: Release resources; may follow finish() or config change if not retained.
10

Intent filter declared in?

AAndroidManifest.xml (or dynamic)
Bcolors.xml
CGradle wrapper
DR.java
Explanation: Manifest intent-filter elements declare supported actions/categories/data.

10 Advanced Activities & Intents MCQs

11

Activity Result API replaces?

AstartActivityForResult (deprecated pattern)
BServices
CFragments only
DADB
Explanation: registerForActivityResult with ActivityResultContracts is the modern approach.
12

singleTop launch mode?

AReuses existing instance if on top of stack
BAlways new task
CNo back stack
DKill app
Explanation: If Activity already at top, onNewIntent instead of new instance.
13

taskAffinity affects?

AWhich task stack Activity prefers
BGradle version
CDex size
DIcon density
Explanation: Affinity groups Activities into tasks for recents and navigation.
14

FLAG_ACTIVITY_CLEAR_TOP?

AClears Activities above target in stack
BDisables animation
CSigns APK
DEnables VPN
Explanation: Often used with singleTop to return to existing Activity state.
15

onSaveInstanceState purpose?

ASave transient UI state across destruction
BPermanent database
CPlay Store
DNetwork cache
Explanation: Bundle restored in onCreate for rotation/process death if implemented.
16

Deep link intent-filter uses?

Aandroid:scheme, host, pathPrefix in data
BOnly category DEFAULT
Ctools:context
DR.string
Explanation: Data elements match URIs for App Links and deep navigation.
17

Parcelable vs Serializable for Intent extras?

AParcelable preferred — faster IPC
BSerializable always required
CNeither works
DJSON only
Explanation: Parcelable optimized for Android; use @Parcelize in Kotlin.
18

onNewIntent when?

AsingleTop/singleTask delivers new Intent to existing instance
BFirst create only
CNever
DService start
Explanation: Update UI when Activity reused at top of stack.
19

Process death vs configuration change?

AConfig change may recreate Activity; process death kills entire process
BSame
CNeither recreates
DOnly emulator
Explanation: Rotation triggers config change; low memory kills process — restore state accordingly.
20

choosers for implicit intents?

AIntent.createChooser wraps share intent
BManifest only
CProGuard
DViewBinding
Explanation: Chooser shows disambiguation dialog for share/send actions.
Click an option to select, then check answers.

Activities & Intents Interview Q&A

15 topic-focused questions for interviews and revision.

1Explain the Activity lifecycle in order when opening and leaving an app.medium
Answer: onCreate → onStart → onResume when entering; onPause → onStop → onDestroy when leaving/finishing (with onRestart/onStart if returning).
2Difference between explicit and implicit Intent.easy
Answer: Explicit names the component class; implicit declares action/data type and lets the system resolve matching apps.
3How do you pass data to another Activity?easy
Answer: Build Intent with putExtra or putParcelableExtra; startActivity; receiving Activity reads extras in onCreate/intent.
4What is an intent-filter?medium
Answer: Manifest declaration of actions, categories, and data URIs an Activity can handle for implicit intents.
5When is onPause called vs onStop?medium
Answer: onPause when partially obscured; onStop when fully hidden but process may still live.
6Explain launch modes at a high level.hard
Answer: standard (default new instance), singleTop (reuse if top), singleTask/singleInstance alter task/stack behavior.
7How to handle rotation without losing form data?medium
Answer: ViewModel, onSaveInstanceState, or retain non-UI data in repository; avoid holding Activity in static fields.
8What happens if you don't call super.onCreate()?easy
Answer: Runtime crash — framework initialization skipped; always call super in lifecycle overrides.
9How to return result from Activity B to A today?medium
Answer: Use Activity Result API: register launcher in A, B setResult(RESULT_OK, intent) and finish().
10Security consideration with implicit intents.hard
Answer: Don't expose sensitive data to unknown handlers; prefer explicit in-app intents; validate incoming deep links.
11What is task back stack?medium
Answer: Stack of Activities user navigated; Back pops top Activity; tasks shown in Recents.
12Why might startActivity throw ActivityNotFoundException?medium
Answer: No matching component for implicit intent, or explicit class not in manifest/wrong package.
13Explain onRestart.easy
Answer: Called when user returns to stopped Activity from back stack before onStart.
14Can Intent carry large bitmaps?hard
Answer: Avoid — use size limits; prefer file URI, content provider, or shared ViewModel for large payloads.
15Common lifecycle logging exercise purpose?easy
Answer: Overrides with Log.d teach order of callbacks and when UI is visible vs interactive.