Android Activity

Android Activity Frequently asked Interview Questions

Android Activity Frequently asked Interview Questions

Android Activity Frequently asked Interview Questions

Getting ready for an interview? Look here for a wide range of Android Activity-related questions and answers to boost your knowledge. Whether you're new to Android development or a seasoned pro, this page has you covered. Let's ace those Android Activity questions together!

Codecastic
0
Codecastic
0
Codecastic
0
Codecastic
0

On this page

1. Can you explain the Android Activity lifecycle and the significance of each lifecycle method in detail?

The Android Activity lifecycle is a series of steps that manage how an activity behaves throughout its existence. Each step serves a specific purpose in ensuring smooth operation and efficient resource usage in your app.

  1. onCreate(): Called when the activity is first created, it initializes UI components and sets up data structures. It’s where you inflate layout files and bind views.

  2. onStart(): Invoked just before the activity becomes visible to users. Here, register listeners or start animations to prepare for user interaction.

  3. onResume(): The activity enters the foreground and starts interacting with users. Resume paused tasks like video playback or sensor updates.

  4. onPause(): Partially obscured by another activity, this method saves unsaved changes and stops CPU-intensive tasks to conserve resources.

  5. onStop(): Completely hidden from view, release resources not needed while in the background, such as location updates or broadcast receivers.

  6. onDestroy(): Called before the activity is destroyed, either due to system constraints or user action. Perform final cleanup, like closing database connections or stopping services.

  7. onRestart(): Occurs when an activity moves from stopped to started state, typically after being in the background. Reinitialize components released during onStop().

Understanding these lifecycle methods helps you build responsive apps that handle various scenarios smoothly, ensuring a great user experience while managing resources efficiently.

2. What is the difference between a Service and an Activity in Android? When would you choose to use a Service instead of an Activity?

A Service is a background component that performs long-running tasks without user interaction, while an Activity represents a single screen with a user interface. Services are used for operations like network transactions or playing music, whereas Activities handle UI-related tasks.

Choose a Service when:
1. Task execution doesn’t require user input.
2. Operation should continue even if the app isn’t visible.
3. Resource consumption is minimal to avoid affecting other apps.

Use an Activity when:
1. User interaction is necessary.
2. Task completion depends on user input.
3. Visual feedback is essential during task execution.

3. Describe the difference between onSaveInstanceState() and onRestoreInstanceState() methods in Android Activities. When are these methods called?

onSaveInstanceState() and onRestoreInstanceState() are methods in Android Activities that handle the preservation and restoration of an Activity’s state during configuration changes or when the system kills the process.

onSaveInstanceState() is called before the Activity is destroyed, allowing you to save its current state into a Bundle. This method is typically invoked when the device undergoes a configuration change (e.g., screen rotation) or when the system decides to kill the Activity due to low memory. It is not called when the user explicitly closes the Activity.

onRestoreInstanceState() is called after onStart() and before onResume(), enabling you to restore the saved state from the Bundle provided by onSaveInstanceState(). This method is only called if there was a previous saved state; otherwise, it won’t be triggered.

4. In what scenarios would you use the launch modes “singleTop”, “singleTask”, and “singleInstance”? Explain their significance and how they impact the back stack of activities.

singleTop is used when an activity should only have one instance at the top of the back stack. If it’s already on top, a new instance won’t be created; instead, onNewIntent() will be called. This prevents duplicate instances and conserves resources.

singleTask creates a new task with the activity as its root if no existing tasks hold an instance. If there’s an existing instance in another task, that task comes to the foreground, clearing activities above it. Useful for navigation or clearing unrelated activities.

singleInstance behaves like singleTask but doesn’t allow other activities within the same task. It ensures the activity remains separate from others, useful for modal dialogs or floating windows.

These launch modes impact the back stack by controlling how activities are organised, preventing duplicates, and managing task transitions.

5. How would you handle screen orientation changes in an Android Activity, and why is it important to manage such changes?

Handling screen orientation changes in an Android Activity involves overriding the onSaveInstanceState() and onRestoreInstanceState() methods, or using ViewModel to store UI data. Additionally, you can lock the orientation by setting android:screenOrientation in the manifest file.

Overriding onSaveInstanceState() allows saving the current state of the activity before it’s destroyed due to configuration changes. The saved state is passed as a Bundle to onRestoreInstanceState(), where the previous state can be restored.

Using ViewModel helps retain UI-related data across configuration changes without requiring manual handling of onSaveInstanceState(). ViewModel survives configuration changes, allowing data persistence.

Managing orientation changes is crucial for providing seamless user experience, preventing loss of user input, and avoiding resource-intensive operations like network requests from being executed repeatedly during such changes.

6. Explain the difference between startActivityForResult() and startActivity() methods. When would you use one over the other?

startActivity() initiates a new activity without expecting any result, while startActivityForResult() starts an activity and expects a result back. Use startActivity() for simple navigation between activities, and startActivityForResult() when you need data from the launched activity.

For example, use startActivityForResult() when opening a contact picker to select a contact, then return the selected contact’s information to the calling activity. In contrast, use startActivity() when navigating from a login screen to a home screen, as no data needs to be returned.

To handle results in the calling activity, override onActivityResult() method, which receives requestCode, resultCode, and Intent containing result data.

Example:

7. Describe how you would use fragments in your Android Activity to optimize a multi-pane layout for different screen sizes or device orientations.

To optimize a multi-pane layout using fragments in an Android Activity, follow these steps:

1. Create reusable fragment classes for each pane, encapsulating their UI and logic.
2. Define layouts for different screen sizes or orientations, using resource qualifiers (e.g., “layout-sw600dp” for larger screens).
3. In the layouts, use tags to reference your fragment classes, specifying unique IDs for each instance.
4. In your Activity’s onCreate method, use FragmentManager to manage fragments based on the current configuration.
5. Use setRetainInstance(true) in fragments if needed, to preserve state during configuration changes.
6. Implement communication between fragments via interfaces/callbacks, with the Activity as mediator.

8. Explain the role of Intent objects in communication between Android components, especially between Activities, and provide examples of different Intent types.

Intent objects facilitate communication between Android components, primarily Activities. They enable navigation and data transfer within an application or to external apps.

Two Intent types exist: explicit and implicit. Explicit Intents target specific components by specifying their class names, while implicit Intents rely on the system to find suitable components based on action, category, and data.

Explicit Intent example:

Copied

Implicit Intent example:

Copied

9. How do you ensure that a sensitive or resource-intensive operation is not performed while your activity is in the background or is partially obscured?

To ensure sensitive or resource-intensive operations are not performed while an activity is in the background or partially obscured, utilise Android’s Activity Lifecycle methods. Specifically, perform these operations within onResume() and onPause(). Start the operation in onResume(), as it is called when the activity becomes visible and active. Pause or stop the operation in onPause(), which is invoked when the activity loses focus or visibility.

For long-running tasks, consider using a Service to handle them independently of the activity lifecycle. This ensures that even if the activity is destroyed, the task continues running in the background.

10. What is the significance of the onActivityResult() method and when is it called?

The onActivityResult() method is significant in managing data returned from activities started by startActivityForResult(). It’s called when the launched activity finishes, returning result code and intent containing additional data. This enables communication between activities, ensuring proper handling of results.

11. How does deep linking function within Android Activities, and what steps would you take to integrate it into your app?

Deep-linking in Android Activities allows users to navigate directly to specific content within an app, bypassing the main screen. It enhances user experience by providing shortcuts and improving discoverability.

To implement deep-linking:

1. Define intent filters: In your activity’s manifest file, add an intent filter with action “android.intent.action.VIEW” and category “android.intent.category.DEFAULT”, “android.intent.category.BROWSABLE”. Specify data URI scheme, host, and path pattern.

Example:

2. Handle incoming intents: In the target activity, override the onNewIntent() method or handle getIntent() in onCreate(). Extract data from the intent and display relevant content.

Copied

12. What are the best practices for managing application memory and battery usage when working with Activities and their lifecycle?

To optimize memory and battery usage in Android Activities, follow these best practices:

1. Utilize Activity lifecycle methods: Implement onPause(), onStop(), and onDestroy() to release resources when the activity is no longer visible or needed.
2. Avoid long-running tasks: Use background services or WorkManager for lengthy operations to prevent blocking the UI thread and draining battery.
3. Minimize network requests: Cache data locally and use efficient APIs like Retrofit with appropriate caching strategies.
4. Optimize layouts: Flatten view hierarchies, use ConstraintLayout, and avoid overdraw by eliminating unnecessary backgrounds.
5. Handle configuration changes: Retain fragments or ViewModel to preserve data during orientation changes, avoiding redundant resource loading.
6. Monitor memory leaks: Utilize tools like LeakCanary to detect and fix memory leaks caused by unhandled references.
7. Employ Battery optimizations: Adhere to Doze mode guidelines, schedule non-urgent tasks using JobScheduler, and minimize wake locks.

13. Explain the concept of task affinity and its impact on the behavior of Android Activities.

Task affinity refers to the relationship between activities and tasks in Android. It determines which task an activity should belong to when launched, affecting the back stack and navigation behavior.

By default, all activities within an app share the same affinity, causing them to reside in a single task. However, developers can modify this by setting the “taskAffinity” attribute in the AndroidManifest.xml file. This allows for custom grouping of activities into separate tasks or even mixing activities from different apps.

Changing task affinity impacts user experience as it alters the order in which activities are presented when navigating through the back stack. For instance, if two activities have different affinities, pressing the back button may not return to the previous activity but instead switch to another task.

14. How do you handle runtime permissions in Android Activities, and why is this an important consideration for modern Android applications?

Runtime permissions in Android Activities are handled using the ActivityCompat.requestPermissions() method and overriding onRequestPermissionsResult(). This process involves checking if a permission is granted with ContextCompat.checkSelfPermission(), requesting it if necessary, and handling the user’s response.

Modern Android applications must consider runtime permissions due to changes introduced in Android 6.0 (API level 23), where users grant permissions at runtime instead of during app installation. This approach enhances user privacy and control over their data while ensuring apps function correctly when accessing sensitive resources.

Example:

15. What is the difference between Parcelable and Serializable, and when is it appropriate to use each in the context of an Android Activity?

Parcelable and Serializable are both interfaces in Android for object serialization. The key difference lies in their performance and implementation.

Parcelable is specifically designed for Android, offering better performance due to its optimized binary format. It requires manual implementation of the Parcelable interface, defining how data is serialized and deserialized. Use Parcelable when passing objects between Activities or Fragments via Intents or Bundles, as it’s more efficient for inter-process communication.

Serializable, part of Java standard library, uses reflection, making it slower and less efficient than Parcelable. It’s easier to implement since classes only need to implement the Serializable interface without additional methods. However, this convenience comes at a cost of increased memory usage and reduced speed.

16. How does Android manage the back stack of activities when navigating through an application, and what are the implications of using the onBackPressed() method?

Android manages the back stack using a last-in, first-out (LIFO) data structure called Task. When navigating through an application, each new Activity is added to the top of the stack. Pressing the back button removes the current Activity and reveals the previous one.

The onBackPressed() method allows developers to override the default behavior when the back button is pressed. By overriding this method, custom actions can be performed before finishing the current Activity or even preventing it from being removed from the stack.

However, improper use of onBackPressed() may lead to unexpected navigation behavior, memory leaks, or app crashes. It’s crucial to consider user experience and ensure that overridden behavior aligns with Android design guidelines and user expectations.

17. What is the significance of using the onTrimMemory() method in activities, and how can you utilize it to reduce memory usage in your application?

The onTrimMemory() method is significant in managing an app’s memory usage, as it helps developers handle low-memory situations. It gets called when the system determines that memory should be reclaimed to free up resources for other apps or processes.

To utilize onTrimMemory(), override this method in your activity and implement appropriate actions based on different memory levels passed as a parameter (TRIM_MEMORY_* constants). For example:

1. TRIM_MEMORY_RUNNING_LOW: Reduce cache size or release objects consuming memory.
2. TRIM_MEMORY_UI_HIDDEN: Release UI-related resources like bitmaps since the user interface is not visible.
3. TRIM_MEMORY_BACKGROUND/TRIM_MEMORY_MODERATE/TRIM_MEMORY_COMPLETE: Free up more resources depending on the severity of the situation.

By responding to these memory level hints, you can optimize your app’s performance and reduce its memory footprint, ensuring smooth operation even under constrained conditions.

18. Can you explain how you would use onSaveInstanceState() and ViewModel to preserve UI state and data during configuration changes, like screen rotations?

To preserve UI state and data during configuration changes, use onSaveInstanceState() and ViewModel together. First, create a ViewModel class extending Android’s ViewModel to store UI-related data. Override onCleared() if necessary for cleanup.

In the Activity, initialize the ViewModel using ViewModelProvider. For transient UI state (e.g., scroll position), save it in onSaveInstanceState(). In onCreate(), restore this state from savedInstanceState Bundle.

For non-transient data (e.g., user input), store it in LiveData objects within ViewModel. Observe these LiveData objects in the Activity, updating UI accordingly. This ensures data survives configuration changes without manual saving/restoring.

Example:

Copied

19. Describe the difference between implicit and explicit intents, and provide examples of each in the context of starting an Activity.

Implicit Intents:

Implicit intents are used when you want the system to find and start an appropriate component for you. You just specify the action you want to perform and let the system choose the best component to handle that action.

Example: Suppose you want to open a web page. You create an intent with the action Intent.ACTION_VIEW and set the URL as data. The system then finds the appropriate web browser app on the device and opens the URL in it.

Explicit Intents:

Explicit intents are used when you exactly know which component you want to start. You specify the component name explicitly in the intent.

Example: Suppose you have an activity called MainActivity and you want to start another activity called SecondActivity. You create an intent, set the component name as SecondActivity, and start the activity using this intent. This way, you directly specify which activity to start.

Last updated -

Mar 25, 2024

Share this page

On this page
Android Activity
1. Can you explain the Android Activity lifecycle and the significance of each lifecycle method in detail?
2. What is the difference between a Service and an Activity in Android? When would you choose to use a Service instead of an Activity?
3. Describe the difference between onSaveInstanceState() and onRestoreInstanceState() methods in Android Activities. When are these methods called?
4. In what scenarios would you use the launch modes “singleTop”, “singleTask”, and “singleInstance”? Explain their significance and how they impact the back stack of activities.
5. How would you handle screen orientation changes in an Android Activity, and why is it important to manage such changes?
6. Explain the difference between startActivityForResult() and startActivity() methods. When would you use one over the other?
7. Describe how you would use fragments in your Android Activity to optimize a multi-pane layout for different screen sizes or device orientations.
8. Explain the role of Intent objects in communication between Android components, especially between Activities, and provide examples of different Intent types.
9. How do you ensure that a sensitive or resource-intensive operation is not performed while your activity is in the background or is partially obscured?
10. What is the significance of the onActivityResult() method and when is it called?
11. How does deep linking function within Android Activities, and what steps would you take to integrate it into your app?
12. What are the best practices for managing application memory and battery usage when working with Activities and their lifecycle?
13. Explain the concept of task affinity and its impact on the behavior of Android Activities.
14. How do you handle runtime permissions in Android Activities, and why is this an important consideration for modern Android applications?
15. What is the difference between Parcelable and Serializable, and when is it appropriate to use each in the context of an Android Activity?
16. How does Android manage the back stack of activities when navigating through an application, and what are the implications of using the onBackPressed() method?
17. What is the significance of using the onTrimMemory() method in activities, and how can you utilize it to reduce memory usage in your application?
18. Can you explain how you would use onSaveInstanceState() and ViewModel to preserve UI state and data during configuration changes, like screen rotations?
19. Describe the difference between implicit and explicit intents, and provide examples of each in the context of starting an Activity.