Friday, May 30, 2025

Android Kotlin Interview Questions for 5 yrs Experience level part 2

 Here is Part 2 of Interview Questions for the 3-5+yrs of Experience level. Get ready for in-depth discussion during a face-to-face interview: 


25. How does Retrofit work in Android?

Retrofit is a type-safe HTTP client for Android and Java that simplifies network calls. You define REST API endpoints as interfaces with annotations for HTTP methods. Retrofit handles creating HTTP requests, parsing JSON/XML responses (via converters like Gson), and returns typed objects. It supports synchronous and asynchronous calls and integrates with coroutines for suspending functions.


 

26. What is Android Jetpack?

Android Jetpack is a set of libraries, tools, and architectural guidance provided by Google to help developers build robust, maintainable, and testable Android apps quickly. It includes components for managing UI, data persistence, background processing, lifecycle management, navigation, and more. Jetpack components follow modern development best practices and reduce boilerplate code, such as LiveData, ViewModel, Room, WorkManager, Navigation, and Paging. Jetpack is designed to work seamlessly with Kotlin and supports backward compatibility with older Android versions.


27. Explain the Navigation Component in Android Jetpack

The Navigation Component simplifies implementing navigation within an Android app. It provides a consistent and declarative way to manage UI navigation through navigation graphs, which define all possible paths and transitions between destinations (activities or fragments). It handles fragment transactions, back-stack management, and deep linking automatically. The Navigation Component also supports passing data between destinations and supports bottom navigation and drawer navigation UI patterns. It reduces boilerplate code and helps maintain navigation state safely during configuration changes.


28. What is View Binding and how is it different from Data Binding?

  • View Binding generates a binding class for each XML layout file, which contains direct references to all views with an ID, allowing type-safe access without findViewById(). It is simpler and has no impact on performance.
  • Data Binding extends View Binding and allows binding expressions in XML layouts that can directly connect UI components to data sources, supporting two-way binding and live updates. Data Binding requires more setup and adds some overhead but is more powerful for reactive UIs.
    In short, View Binding is for safer, easier view access; Data Binding adds data-driven UI features.

29. What is the difference between FragmentTransaction.commit() and commitAllowingStateLoss()?

  • commit(): Safely commits a FragmentTransaction and throws an exception if the commit is attempted after the activity’s state is saved (e.g., during or after onSaveInstanceState()), preventing UI inconsistencies.
  • commitAllowingStateLoss(): Commits the transaction even after the state is saved, allowing potential loss of the fragment state if the system kills the app afterward. Use this cautiously when you are sure the UI changes are non-critical or unavoidable.

30. How do you handle multithreading in Android?

Android supports multiple approaches for multithreading:

  • AsyncTask: Deprecated. Used to run short background tasks and update UI on the main thread.
  • Thread and Handler: Create new threads and communicate with the UI thread via Handlers and MessageQueues.
  • Executors: Manage thread pools for background tasks.
  • Kotlin Coroutines: Recommended modern approach for asynchronous programming with lightweight threads called coroutines.
  • RxJava: Reactive programming library that simplifies asynchronous streams.
    Choosing the right approach depends on complexity, lifecycle awareness, and performance needs.

31. Explain the difference between SingleTop, SingleTask, and SingleInstance launch modes in Android.

These launch modes define how new activities are launched and how they interact with the activity back stack:

  • SingleTop: If the target activity is already at the top of the stack, a new instance is not created; instead, onNewIntent() is called. Otherwise, a new instance is created. Useful for activities like notification handlers.
  • SingleTask: Only one instance of the activity exists in the entire system. If an instance exists in the back stack, it is brought to the front, and onNewIntent() is called. The task will be cleared above the activity.
  • SingleInstance: Like SingleTask but the activity is the only one in its task. No other activities will be part of the task, used for special cases like launcher apps.

32. What is the difference between Parcelable and Bundle?

  • Parcelable: An interface for classes whose instances can be written to and restored from a Parcel, primarily used to pass custom objects between components efficiently. Parcelable requires manual implementation of serialization logic but is faster than Serializable.
  • Bundle: A container for passing data between activities and fragments. It supports primitive types, arrays, and objects that implement Parcelable or Serializable. Bundles are often used with Intents or Fragment arguments but are not a serialization mechanism by themselves.

33. What is the difference between startService() and bindService()?

  • startService(): Starts a service and runs it indefinitely until stopped. It is used for tasks that don’t require interaction with clients, such as playing music or downloading files. The service runs on the main thread by default.
  • bindService(): Establishes a client-server interface to interact with the service. It allows the client to send requests, get results, and communicate with the service while bound. The service only runs as long as one or more clients are bound.

34. What is the difference between HandlerThread and AsyncTask?

  • HandlerThread: A thread with a Looper that can process multiple tasks sequentially via Handlers. It’s useful for long-running background tasks and when you need a message queue.
  • AsyncTask: Designed for short-lived asynchronous tasks with a simple API that executes on a background thread and updates UI on the main thread. It is deprecated because it is prone to memory leaks and poor lifecycle management. HandlerThread offers more control and is better suited for complex, long-running work.

35. How does Android manage memory and garbage collection?

Android uses a managed runtime (ART) which automatically manages memory allocation and garbage collection.

  • When objects are no longer referenced, they become eligible for garbage collection.
  • Garbage collection reclaims memory by freeing unused objects to prevent memory leaks and OutOfMemory errors.
  • ART uses generational garbage collection optimized for mobile devices to reduce pause times.
  • Developers should be cautious with large objects, static references, and contexts to avoid leaks. Tools like LeakCanary help detect memory leaks.

36. What is the difference between implicit and explicit intents?

  • Explicit Intent: Specifies the exact component (activity, service, or broadcast receiver) to start by naming its class. Used for internal app communication, e.g., starting a specific activity within your app.
  • Implicit Intent: Does not specify the component directly. Instead, it declares a general action to perform, allowing the system to find components that can handle it, e.g., sharing content or opening a web page. The system resolves the best match based on intent filters declared in the manifest.

37. What is the Android Application class?

The Application class in Android is a base class containing global application state for the entire app. It is instantiated before any other app components and remains alive throughout the app lifecycle. Developers often subclass Application to initialize libraries, maintain global configurations, or hold shared resources such as singletons. It is declared in the manifest file and provides a centralized place for app-wide initialization.


38. How does the Android Runtime (ART) work?

ART is the Android Runtime environment introduced to replace Dalvik. It executes Android applications by compiling bytecode into native machine code ahead of time (AOT) during app installation, improving performance and startup time. ART also performs garbage collection and manages memory. It supports Just-In-Time (JIT) compilation for further optimization during app execution. ART improves battery life, runtime efficiency, and debugging compared to Dalvik.


39. Explain the difference between onPause() and onStop()

  • onPause(): Called when the activity is partially obscured but still visible (e.g., during a dialog or multi-window mode). This is where you should pause animations, commit unsaved changes, or release resources that don’t need to persist when not in focus.
  • onStop(): Called when the activity is no longer visible to the user. You should release or adjust resources that are needed only while visible, like stopping camera preview or heavy processing. The activity can be destroyed after onStop().

40. What is ANR and how to prevent it?

ANR (Application Not Responding) occurs when the main thread is blocked for too long (usually more than 5 seconds) and the system prompts the user to close or wait. Causes include heavy computations or blocking I/O operations on the main thread.
Prevention:

  • Offload long-running operations to background threads or coroutines.
  • Use AsyncTask, ThreadPools, or WorkManager for background work.
  • Avoid heavy processing or network calls on the UI thread.
  • Optimize UI rendering and database queries.

41. What are sealed classes in Kotlin and their use in Android?

Sealed classes restrict class hierarchies to a limited set of types known at compile-time. They are used to represent restricted polymorphic types, often for modeling state or results (e.g., success, error, loading).
In Android, sealed classes are frequently used with ViewModels to represent UI states cleanly, enabling exhaustive when statements without needing an else clause, improving type safety and clarity.


42. What is the difference between MutableLiveData and LiveData?

  • LiveData: Provides observable data but is immutable from the observer’s perspective — data can only be observed, not changed.
  • MutableLiveData: A subclass of LiveData that exposes public methods to update the value (setValue() or postValue()), allowing data to be changed by the ViewModel or data layer.
    Typically, ViewModels expose LiveData publicly to UI components to observe and keep MutableLiveData private to control modifications.

43. How do you optimize Android app performance?

Key ways include:

  • Efficient use of memory and avoiding memory leaks.
  • Offloading heavy operations from the main thread to background threads.
  • Using RecyclerView with ViewHolder pattern for lists.
  • Reducing overdraw by optimizing layouts.
  • Using appropriate image loading libraries (Glide, Picasso) with caching.
  • Minimizing app size by removing unused resources.
  • Using Jetpack libraries and architecture components for better lifecycle management and performance.
  • Profiling with Android Profiler tools and fixing bottlenecks.

44. What is an APK and what are its components?

APK (Android Package) is the file format used to distribute and install Android apps. Components inside an APK include:

  • classes.dex: Compiled bytecode files.
  • AndroidManifest.xml: App metadata and component declarations.
  • resources.arsc: Precompiled resources like strings and layouts.
  • lib/: Native libraries.
  • assets/: Raw asset files.
  • META-INF/: Signature and certificate files for security.

45. What is the difference between ProGuard and R8?

  • ProGuard: A tool that shrinks, optimizes, and obfuscates Java bytecode to reduce APK size and make reverse engineering harder. Requires configuration files and was the default in older Android builds.
  • R8: The new default code shrinker and optimizer that combines the features of ProGuard and the D8 dex compiler, offering faster builds and better optimizations. R8 automatically applies rules and is fully compatible with ProGuard configs.

46. What is a Content Provider in Android?

A Content Provider manages access to a structured set of data and enables data sharing between different applications. It encapsulates the data, enforces permissions, and provides a standard interface to query, insert, update, or delete data using URIs (Uniform Resource Identifiers). Content Providers are used to share data such as contacts, media, or custom app data securely across apps. They handle concurrency, transactions, and notify observers of data changes. To use a Content Provider, apps use a ContentResolver to interact with it.


47. What is the difference between onSaveInstanceState() and onRestoreInstanceState()?

  • onSaveInstanceState(): Called before an activity is destroyed (e.g., due to rotation or backgrounding) to save transient UI state data in a Bundle. It is used to save small pieces of information like form inputs or scroll positions.
  • onRestoreInstanceState(): Called after onStart() only if there is saved state available, to restore UI state from the saved Bundle. It complements onCreate(), which can also receive the saved Bundle to restore state. These methods ensure UI consistency across configuration changes or process recreation.

48. What is a PendingIntent and when is it used?

A PendingIntent is a token that you give to another application (e.g., NotificationManager, AlarmManager, or other system services) which allows that application to execute your app's code (usually an Intent) on your app’s behalf at a later time. It is used when you want another app or service to perform an action with your app’s permissions, such as launching an activity, starting a service, or sending a broadcast. Common use cases include notifications, alarms, and widgets.


49. How do you handle API level compatibility in Android?

Handling API compatibility involves:

  • Using compileSdkVersion for latest API features during build.
  • Setting minSdkVersion to define the lowest Android version your app supports.
  • Using runtime checks (Build.VERSION.SDK_INT) to conditionally execute code depending on the API level.
  • Using support libraries or Jetpack libraries which provide backward-compatible implementations.
  • Employing feature detection rather than relying solely on API levels.
  • Testing on multiple devices and emulators for various Android versions.

50. What is the role of ProGuard rules in Android?

ProGuard rules guide the code shrinking, obfuscation, and optimization process. They tell ProGuard or R8 which classes, methods, or fields to keep (prevent from being removed or renamed), which to obfuscate, or which optimizations to apply or skip. Proper rules are important to avoid breaking code that relies on reflection, serialization, or external libraries. Common rules include keeping model classes, library classes, annotation usage, and entry points such as activities or services.


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...