Friday, May 30, 2025

Android Kotlin Interview Questions for Intermediate level part 2

  Here are Interview Questions for the Intermediate level 1-3 yrs of Experience level. Get ready for in-depth discussion during a face-to-face interview:


26. What are the different ways to pass data between Android components?

Answer:

  • Intent extras: Pass data between activities or services using key-value pairs.
  • Bundles: Pass data in fragments or during state saving.
  • SharedPreferences: Persist small key-value data accessible across app components.
  • Singletons or Application class: Store global app data.
  • ViewModel shared between fragments: Share data in the same activity lifecycle.
  • Database or cache: Store persistent data accessible anywhere.

27. What is a Content Provider? Why is it used?

Answer:

Content Providers manage access to a structured set of data, allowing data sharing between apps in a secure and controlled way.

  • Provide CRUD (Create, Read, Update, Delete) operations.
  • Used to share data like contacts, media, or custom app data.
  • Accessed through a standardized URI.

Example: The Contacts app uses a content provider to expose contact data to other apps.


28. How does Android handle permissions?

Answer:

  • Normal permissions: Granted automatically (e.g., internet access).
  • Dangerous permissions: Require runtime user approval (e.g., camera, location).
  • Use checkSelfPermission() to check, and requestPermissions() to ask users.
  • Handle the permission callback in onRequestPermissionsResult().
  • From Android 11+, Scoped Storage restricts file access.
  • Best practice: Ask permissions contextually when needed, explain why to the user.

29. What is Data Binding and how is it useful?

Answer:

Data Binding connects UI components in layouts directly to data sources in the app, reducing boilerplate code.

  • Eliminates findViewById() calls.
  • Supports two-way binding for editable fields.
  • Improves performance by reducing the need for observers.
  • Integrates seamlessly with ViewModel and LiveData for reactive UI.

Example:

xml

CopyEdit

<TextView android:text="@{viewModel.userName}"/>


30. How do you implement pagination in Android?

Answer:

Pagination helps load data incrementally to reduce memory usage and improve performance.

  • Use the Paging library from Jetpack which supports loading data page-by-page from network or database.
  • Supports data source invalidation, boundary callbacks.
  • Works with RecyclerView for smooth scrolling.

Basic flow:

  • Define a PagingSource that fetches data pages.
  • Use a Pager object to create a PagingData.
  • Submit the PagingData to a PagingDataAdapter attached to RecyclerView.

31. What are Android Services and how do they work?

Answer:

Android Services are components that perform long-running operations in the background without a user interface. They are used when an app needs to perform work even if the user switches to another app or the device goes to sleep.

  • Types of Services:
    • Started Service: Starts when an app calls startService() and runs indefinitely, even if the caller is destroyed. It must stop itself with stopSelf() or be stopped by others.
    • Bound Service: Allows components (like activities) to bind to the service and communicate via Binder interface. It runs as long as one or more clients are bound.
    • Foreground Service: A service with a persistent notification, indicating to users that it is running and important (e.g., music player).
  • Services run on the main thread by default, so developers should offload intensive tasks to worker threads.

32. What is the Android Manifest file?

Answer:

AndroidManifest.xml is a required configuration file in every Android app that provides essential information to the Android system about the app.

  • Declares components: Activities, Services, Broadcast Receivers, Content Providers.
  • Specifies app permissions, hardware and software features required.
  • Declares app metadata such as minimum SDK version, theme, app icon, launcher activity.
  • Controls app behavior with intent filters and process settings.

33. What is the difference between Serializable and Parcelable?

Answer:

Both are used for passing objects between components or saving state, but they differ significantly:

  • Serializable: A standard Java interface, easy to implement (no methods required), but slower because it uses reflection and creates many temporary objects.
  • Parcelable: Android-specific, requires explicit implementation of serialization logic using writeToParcel() and CREATOR, but is faster and more memory-efficient, preferred for Android development.

34. How do you improve app security?

Answer:

  • Use ProGuard/R8 to obfuscate code, making reverse engineering difficult.
  • Secure sensitive data using Android Keystore for cryptographic keys.
  • Encrypt data stored on the device using EncryptedSharedPreferences or SQLCipher.
  • Use HTTPS for all network communication.
  • Minimize app permissions and request them only at runtime when needed.
  • Use biometric authentication or strong user authentication.
  • Validate and sanitize all inputs to prevent injection attacks.
  • Keep dependencies up-to-date and avoid insecure libraries.

35. What is the difference between Handler, Looper, and Thread?

Answer:

  • Thread: A separate unit of execution used to perform background operations.
  • Looper: Manages a message queue for a thread, allowing it to process messages or runnable objects sequentially.
  • Handler: Posts messages or runnables to a Looper’s message queue and processes them on the associated thread.

In Android, the main thread has a Looper that handles UI events and message processing.


36. How does Android handle memory management?

Answer:

  • Android uses Garbage Collection (GC) on the Dalvik or ART runtime to automatically free unused objects.
  • Memory is limited per app, so developers must avoid memory leaks (e.g., by avoiding static references to contexts).
  • Use tools like LeakCanary and Android Profiler to detect leaks.
  • Properly manage lifecycle of components to release references.
  • Use efficient data structures and avoid large memory allocations on the main thread.

37. Explain how Broadcast Receivers are registered and when to use each method.

Answer:

  • Static Registration: Defined in AndroidManifest.xml. Useful for system-wide broadcasts (e.g., boot completed). Runs even if app is not running but has limitations on newer Android versions for implicit broadcasts.
  • Dynamic Registration: Done programmatically in code using registerReceiver(). Limited to the app lifecycle, recommended for broadcasts while the app is running. Allows for fine control and unregistering when not needed.

38. What is the difference between HandlerThread and AsyncTask?

Answer:

  • HandlerThread: A thread with a Looper to process messages or runnables sequentially on its own thread. Good for background tasks requiring message handling or sequential execution.
  • AsyncTask (deprecated): Simplifies background operations and UI updates but has limitations:
    • Tied to activity lifecycle, can cause memory leaks.
    • Limited thread pool size.
    • Deprecated in favor of Coroutines or WorkManager.

39. How do you manage multiple screen sizes in Android?

Answer:

  • Use ConstraintLayout or FlexboxLayout for responsive UIs.
  • Provide different layout resources for different screen sizes and densities using resource qualifiers (e.g., layout-sw600dp).
  • Use dp (density-independent pixels) and sp (scale-independent pixels) for sizing.
  • Support multiple orientations and test on emulators and real devices.
  • Use vector drawables instead of raster images for scalability.

40. What is the Android Navigation Component?

Answer:

The Navigation Component is a Jetpack library that simplifies navigation between fragments and activities.

  • Provides a navigation graph to define all navigation paths.
  • Handles fragment transactions and back stack automatically.
  • Supports deep linking and type-safe argument passing.
  • Works well with ViewModel and LiveData for reactive UI.
  • Simplifies managing complex navigation flows, especially with bottom navigation or side drawers.

41. What is LiveData and how is it different from Observable?

Answer:

LiveData is a lifecycle-aware observable data holder provided by Android Jetpack Architecture Components. It respects the lifecycle of app components such as activities, fragments, and services, ensuring that LiveData only updates UI observers when they are in an active lifecycle state (e.g., STARTED or RESUMED).

  • Automatically handles lifecycle management, preventing memory leaks.
  • Observers are only notified when the app component is active.
  • Can be combined with ViewModel for UI-related data.
  • Supports data binding integration.

Observable (from RxJava or other libraries) is a more general reactive stream which requires manual lifecycle management and can emit data irrespective of component lifecycle, risking memory leaks if not handled carefully.


42. What are some common memory leaks in Android and how do you prevent them?

Answer:

Common causes of memory leaks in Android:

  • Holding references to Context: Static variables or long-lived objects holding onto activity/context references prevent garbage collection.
  • Anonymous inner classes or Handlers: If these hold implicit references to outer classes (e.g., activities).
  • Unregistered BroadcastReceivers or Listeners: Not unregistering them leads to leaks.
  • AsyncTasks: Tied to activity lifecycle; if activity is destroyed before task completes, leaks occur.

Prevention:

  • Use application context where possible.
  • Use weak references to context or views.
  • Properly unregister receivers and listeners.
  • Use lifecycle-aware components like ViewModel, LiveData.
  • Use tools like LeakCanary to detect leaks.

43. Explain ViewModel and its lifecycle.

Answer:

ViewModel is a lifecycle-aware class designed to store and manage UI-related data in a way that survives configuration changes such as screen rotations.

  • Created per scope (usually Activity or Fragment).
  • Retained as long as the scope is alive, even through configuration changes.
  • Cleared when the scope is finished (activity destroyed).
  • Helps separate UI data from UI controller code, improving testability and separation of concerns.
  • Often used with LiveData to provide reactive data updates.

44. What is a Fragment and how is it different from an Activity?

Answer:

  • Fragment: A reusable UI component or portion of UI with its own lifecycle that can be combined in activities. Fragments cannot run independently and must be hosted by an Activity.
  • Activity: Represents a single screen with a UI, serves as the entry point for user interactions.

Differences:

  • Fragments allow modular and flexible UI designs (especially on tablets).
  • Fragments have their own lifecycle but depend on the host activity lifecycle.
  • Multiple fragments can be combined in a single activity.
  • Activities are managed by the OS directly, while fragments are managed by the FragmentManager.

45. What are some ways to improve battery performance of an Android app?

Answer:

  • Minimize background work and schedule background tasks using WorkManager or JobScheduler with constraints.
  • Use foreground services only when necessary.
  • Avoid frequent or unnecessary wake locks.
  • Optimize network calls: batch, compress data, avoid polling.
  • Use efficient location services with proper intervals or geofencing.
  • Avoid excessive use of sensors or animations.
  • Use Doze mode and App Standby APIs to respect system optimizations.
  • Profile power consumption with Battery Historian and Android Profiler.

46. What is View Binding and how does it differ from Data Binding?

Answer:

  • View Binding: Generates a binding class for each XML layout file, allowing safe and direct references to views without findViewById(). It is simpler and doesn’t support expressions or two-way data binding.
  • Data Binding: More powerful; allows binding UI components to data sources declaratively using expressions in XML, supports two-way binding, and can observe LiveData or Observable data.

Use View Binding when you want type-safe view references without extra overhead, and Data Binding when you want to reduce boilerplate with UI logic tied directly to data.


47. What is Retrofit and why is it preferred for network calls?

Answer:

Retrofit is a popular type-safe HTTP client for Android and Java, developed by Square, used to simplify REST API consumption.

Features:

  • Converts HTTP API into Java/Kotlin interfaces.
  • Supports synchronous and asynchronous requests.
  • Supports JSON parsing with converters like Gson or Moshi.
  • Easy error handling and request cancellation.
  • Supports interceptors for logging or headers.
  • Clean and maintainable code structure.

Retrofit abstracts networking code, handles threading, and works well with Kotlin coroutines for asynchronous calls.


48. What are Kotlin Coroutines and how do they compare to RxJava?

Answer:

  • Kotlin Coroutines: Lightweight threads for asynchronous programming built into Kotlin. They provide a simple, sequential code style for async tasks and manage cancellation and exceptions easily.
  • RxJava: A reactive programming library based on Observables, supporting complex asynchronous event streams, chaining, and operators.

Comparison:

  • Coroutines are simpler to learn and use for sequential async code.
  • RxJava is more powerful for complex reactive streams, transformations, and event handling.
  • Coroutines integrate naturally with Kotlin and Jetpack.
  • RxJava has a larger ecosystem but more boilerplate.

49. How do you implement caching in Android apps?

Answer:

  • Use Room database or SQLite to cache persistent data locally.
  • Use SharedPreferences for small key-value pairs.
  • Use in-memory cache like LruCache for temporary data.
  • Use libraries like Glide or Picasso for image caching.
  • Cache network responses using OkHttp's built-in caching mechanisms.
  • Use WorkManager or sync adapters to update cache periodically.

Caching improves performance and reduces network usage.


50. What are PendingIntents and when are they used?

Answer:

A PendingIntent is a token that you give to another app (e.g., NotificationManager, AlarmManager), which allows that app to perform an action on your app’s behalf in the future.

  • Used in notifications to launch activities or services when user interacts.
  • Used in alarms to trigger tasks at a specific time.
  • Used for widgets to trigger app actions.
  • Wraps an Intent that will be executed later with the same permissions as your app.

No comments:

Post a Comment

Top 30 interview questions

Android Development Interview Q&A (5+ Years Experience) Android Development Fundamentals Q: What are the main Android app components and...