Do you want to master Android app development but don't know how to organize your code, manage screens, or connect components? A deep understanding of activities , intents , and fragments is essential. These pillars of Google's operating system allow you to create robust, scalable applications with an excellent user experience.
Below, you'll find the definitive and up-to-date guide on what activities, intents, and fragments are in Android . You'll explore their lifecycles, how they communicate, common mistakes, their differences, and discover practical examples and best practices drawn from official documentation, experienced developers, and the best educational resources in the ecosystem.
What is an Activity in Android?

An Activity is the basic component upon which the user interface in Android is structured. Each screen with which the user can interact is represented by an Activity. The Activity is the central unit of interaction, responsible for managing events, displaying information, and orchestrating the different components that make up the application.
- Screenshot: Every time you open an app and see a screen (login, profile, settings), you are actually navigating between different activities.
- Fragment container: Activities can manage and operate multiple fragments, allowing for more dynamic and modular interfaces.
- Interaction responsibility: They manage the response logic to user events, such as touches, hardware buttons, or orientation changes.
Activities are the main gateway to most applications. Therefore, it's essential to understand how they are declared, managed, and how they communicate with each other and the rest of the system.
In the File AndroidManifest.xml of your project, all activities must be explicitly declared:
The intent filter above indicates that the activity is the app's launch point. This means that when the user taps the icon, this screen will be the first to open.
Key features of the activities:
- Independence: Each activity has its own life cycle and can exist independently.
- Activity Stacks: Android manages a "stack" of activities. When you open a new one, the previous one is paused (and vice versa).
- Communication: Activities can start other activities (from the same app or from other apps) using intents.
Basic initialization example
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Initializing views, receiving data from the Intent, starting fragments, etc. }
The method onCreate() It's the entry point for each activity. The interface (XML layout) is inflated here, variables, receivers, and views are initialized, and business logic can begin.
Activity Life Cycle in Android
The lifecycle of an activity is the sequence of states a screen goes through as the user interacts with it or other applications. Understanding this cycle is fundamental for:
- Avoid errors such as data loss or unexpected shutdowns.
- Optimize resources (memory, battery).
- Provide a seamless user experience.
The main methods that the Android system calls according to the state transition are:
- onCreate(): Initialization, layout inflation, recovery of previous state.
- onStart(): The activity becomes visible, but cannot yet be interacted with.
- onResume(): The activity is in the foreground and the user can interact.
- onPause(): Another activity takes focus, but the current one remains visible (e.g., floating dialog).
- onStop(): The activity becomes invisible (the user switches tasks).
- onRestart(): When the activity returns to focus after a
onStop(). - onDestroy(): The activity is about to be deleted from memory.
Why should you master this? Because each method is an opportunity to:
- Save user status (for example, text in forms or position in lists).
- Pausing animations or audio (available in
onPause()yonResume()). - Stop services and tasks that you don't need in the background.
- Prevent data loss during configuration changes (screen rotation, language change, etc.).
Lifecycle management is especially important for experiences like games, media playback, banking apps, or any application with complex logic.
What is an Intent in Android?

An Intent is a messaging object used by Android to communicate with each other (activities, services, broadcast receivers, etc.). It's the way to request an action, send data, or start processes within the app or with other applications and system services.
How do Intents work?
- Start an activity: Navigate between screens within an app or open a screen from another app.
- Launch services: Run background tasks, such as downloads or syncing.
- Broadcast: Send notifications to the entire system or registered apps (e.g., network change, battery charging).
- Communicate data (Extras): Pass key-value parameters or data packets between components.
Types of Intents:
- Explicit intents: You know the exact class of the target component. These are used to navigate between your own components.
- Implicit intents: You request a general action and let Android decide which component (your app or another) handles it. Examples: open a URL in the browser, share an image, select a contact, etc.
Using implicit intents is one of Android's great advantages: your app can integrate with hundreds of other apps without knowing them in advance, following common standards (view, edit, share, etc.).
Basic syntax
// Explicit Intent val intent = Intent(this, SecondActivity::class.java) intent.putExtra("name", "John") startActivity(intent) // Implicit Intent val intent = Intent(Intent.ACTION_VIEW) intent.data = Uri.parse("https://www.google.com") startActivity(intent)
Main parts of an Intent:
- Action: Indicates the action (view, send, edit, share…)
- Order date: A URI with the information to be processed (link, contact, etc.)
- Component: The specific destination for explicit intents
- Category: Additional category, as if it is the launcher activity
- Extras: Additional data key-value pairs
- flags: They mark how the target activity should behave with respect to the stack and history
The official Android documentation recommends using explicit intents to start services, for security reasons , and using implicit intents for general requests between apps.
Frequent uses of Intents
- Navigate between app screens
- Open the browser, maps, email, camera, etc.
- Sharing native content with other apps
- Listening to system events using BroadcastReceiver
- Run deferred tasks with PendingIntent (notifications, alarms, widgets)
What is a Fragment in Android?

A Fragment is a modular and reusable section of the user interface, along with its own logic, that resides within an Activity. Fragments were created to enhance code reuse and build dynamic and adaptable interfaces, which are especially valuable on devices with different screen sizes (mobile phones, tablets, foldable phones).
- Fragments = LEGO UI pieces: They can be dynamically combined, exchanged and rearranged in an activity.
- They can have their own life cycle, managed by the containing activity.
- Reusable: The same fragment can be used in different contexts within the app.
- full flexibility: Change fragments on the fly based on navigation, orientation, or device type.
Main advantages of fragments
- Modularity: Break down complex screens into simpler, more manageable parts.
- Reuse: The same fragment can be inserted into different activities or combinations.
- Adaptability: They allow you to display multiple fragments at once on tablets, but only one on mobile phones.
- Transactions and stack: Fragments can be added, replaced, or removed dynamically, with animations and history management.
- Compatibility: They work well with tabbed browsers, ViewPager, BottomNavigationView, etc.
Basic fragment example
class MyFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.my_fragment_layout, container, false) } }
The fragment is "inflated" and returned as a view. It is then added to the activity using the FragmentManager:
supportFragmentManager.beginTransaction() .replace(R.containerid, MyFragment()) .commit()
Fragment life cycle
- onAttach(): The fragment is associated with the activity
- onCreate(): Initializes state unrelated to the user interface
- onCreateView(): Inflates the interface and returns it
- onViewCreated(): Initializes view elements
- onResume()/onPause()/onDestroy(): Easy to understand if you know the Activity lifecycle
This cycle allows you to manage resource initialization and release in a granular way, optimizing performance and user experience.
How to declare and use fragments
- In XML: You can include them directly using the tag
<fragment>within the layout of the activity. - By code: Using
FragmentManageryFragmentTransactionto dynamically add, replace, or remove fragments.
Example in XML:
Fragment transactions
- add(): Adds a fragment to the container.
- replace(): Replaces the current fragment with another one in the same container.
- remove(): Removes a fragment from the container.
- addToBackStack(): Allows the user to navigate back through the snippet history.
Communication between fragments and activities
- A fragment can communicate with its containing activity through interfaces, using methods like
getActivity()to access the activity instance. - An activity can access fragments by using
findFragmentById()ofindFragmentByTag(). - Faced with the need to communicate fragments with each other: the ideal is to delegate communication to the activity, which acts as a mediator.
Intents and Deep Intent Filters
To understand architecture and security in Android, it is key to understand how intents relate to intent filters declared in the AndroidManifest.xml.
What is an intent filter?
- Specifies what types of intents a component can receive.
- Allows other applications or the system to invoke your component, provided the intent matches the filter.
Example intent filter for an activity that receives shared texts:
Structure of intent filters
- : The action of the intent (for example,
ACTION_SENDto share,ACTION_VIEWto view resources). - : Groups components that can receive the intent.
CATEGORY_DEFAULTit is the most common. - : Defines the MIME types, URIs, and schemes that the component accepts (e.g., text, images, files).
These filters allow your app to be invoked by other apps, but also limit what actions it is allowed to perform.
Intent Resolution: How Does Android Decide What to Open?
- When an implicit intent is sent, Android looks for registered components whose filter matches the action, category, and data type of the intent.
- If multiple filters match, display a selector to allow the user to choose.
Good practices in security and design
- Use restrictive filters: Don't declare intent filters that are too general, so as not to expose your app to unwanted calls from other apps.
- Controls the attribute
android:exported: Specifies whether the component is accessible from outside your app. If you don't want to allow it, set it tofalse. - Use explicit intents to start your own internal services and activities.
Important Note: Since Android 12, it is mandatory to explicitly set android:exported in all components that have intent filters, otherwise the application will fail to install.
PendingIntent: Deferred Intents and Security
A PendingIntent is a wrapper for an Intent that allows another app or the system itself to execute the intent on behalf of your application, with the same permissions. It's essential for notifications, alarms, widgets, quick actions, and more.
- Example: When the user taps a notification, the actual action (opening activity, running service) is encapsulated in a PendingIntent.
- Mutability and immutability: Since recent versions, you must specify whether the PendingIntent is mutable (can be modified) or immutable (cannot be modified).
When to use PendingIntent
- So that the system runs your code even if your app is not in the foreground.
- When you want to delegate to an external component (example: desktop widgets, alarms, quick replies in notifications).
Best practices with PendingIntent
- Preferably use
FLAG_IMMUTABLEif the intent does not need to be modified by other apps. - If you need the intent to be modifiable (notification replies, chat bubbles), use
FLAG_MUTABLEand make sure the base intent has all the relevant information secure. - Use explicit intents inside PendingIntents to prevent other apps from manipulating the action's destination.
Transactions and Dynamic Fragment Management
One of the most powerful advantages of fragments is their ability to be dynamically managed during app execution . Let's see how to do it professionally.
Management using FragmentManager and FragmentTransaction
- FragmentManager: It is the class that manages operations with fragments in an activity (add, remove, replace).
- FragmentTransaction: A “transaction” is a set of changes that you can apply at once (e.g., replace the current fragment, add another fragment to the stack, combine animations).
Example:
val transaction = supportFragmentManager.beginTransaction() transaction.replace(R.id.fragment_container, NewFragment()) transaction.addToBackStack(null) // Allows you to return to the previous fragment by clicking "Back" transaction.commit()
Back Stack
- Allows the user to navigate back between fragments as if switching screens.
- Each
addToBackStack()Add the transaction to the stack. If you don't use it, the previous fragment is destroyed and you can't return to it with the "Back" button.
Types of fragments provided by Android
- DialogFragment: Displays a floating dialog box over the activity.
- ListFragment: Provides lists of items within a fragment.
- PreferenceFragment: Manage preference lists.
Communication between Fragments and Activities: Patterns and Best Practices

One of the challenges when working with fragments is efficient communication between them, and between the fragments and the main activity.
Communication fragment → activity
- A fragment can call public methods of the containing activity using
getActivity(). - It can trigger events and notify the activity of changes.
Communication activity → fragment
- The activity can search for fragments created using
findFragmentById()ofindFragmentByTag()and call its public methods.
Communication fragment ↔ fragment (via activity)
- Fragments should never communicate directly. Instead, they use the activity as a mediator (using interfaces or events).
- This promotes a decoupled architecture and makes it easier to maintain or expand the app.
Communication interface example
// In source fragment interface OnArticuloSelectedListener { fun onArticuloSelected(text: String) } // In the activity that implements the interface class MainActivity : AppCompatActivity(), OnArticuloSelectedListener { override fun onArticuloSelected(text: String) { // Logic to respond to the fragment event } }
Real-World Use Cases for Activities, Intents, and Fragments

- Messaging apps: The chat list can be a fragment; when you open one, the conversation appears as another fragment in the same activity (especially on tablets).
- News apps: One fragment shows the list of headlines, another the selected news.
- Banking apps: Security and communication levels between separate activities (login, operations, notifications).
- Multimedia Apps: Extensive use of intents to open galleries, share, play audio/video in external apps.
- Widgets and notifications: Using PendingIntent for quick actions from outside the main app.
Common Mistakes and How to Avoid Them
- Do not record activities/fragments in the manifest: Without a declaration they cannot be opened.
- Confuse explicit and implicit intents: Using implicits where it should be explicit causes security and functionality errors.
- Forget
addToBackStack()in fragment transactions: The user will not be able to return to the previous fragment. - Data loss on configuration changes: Not saving states correctly in
onSaveInstanceState(). - Direct and coupled communication between fragments: Making fragments dependent on each other makes maintenance and extensibility difficult.
- Not properly managing permissions on intents that require access to sensitive data (contacts, storage, location).
Good Practices and Advanced Recommendations
- Always validate data received by extras in intents. You may receive malicious intents if you export components.
- Use SafeArgs and Navigation Component for safer and more structured navigation between fragments and activities.
- Rely on architectural patterns (MVVM, MVP, Clean Architecture) to decouple business logic from the UI.
- Break complex activities into multiple fragments to improve maintainability.
- Carefully control the lifecycle to avoid memory leaks and locked resources.
References and Recommended Resources
- Official Guide to Activities at Android Developers
- Complete Guide to Intents and Intent Filters
- Android Fragments Documentation
- Analysis of activities vs. fragments by expert developers
- Practical tutorials on using fragments
Mastering the concepts of activities , intents , and fragments is the first step in developing efficient, robust Android applications that meet the demands of modern devices and user expectations. Proper separation of responsibilities, understanding the app lifecycle, using secure communication between components, and employing modular design will enable you to implement scalable, professional-quality apps.
Table of Contents
- 1 What is an Activity in Android?
- 2 Activity Life Cycle in Android
- 3 What is an Intent in Android?
- 4 What is a Fragment in Android?
- 5 Intents and Deep Intent Filters
- 6 PendingIntent: Deferred Intents and Security
- 7 Transactions and Dynamic Fragment Management
- 8 Communication between Fragments and Activities: Patterns and Best Practices
- 9 Real-World Use Cases for Activities, Intents, and Fragments
- 10 Common Mistakes and How to Avoid Them
- 11 Good Practices and Advanced Recommendations
- 12 References and Recommended Resources