Component Flashcards
What is the purpose of a ViewModel?
It is used to store and manage UI-related data.
How does a ViewModel handle configuration changes?
It retains UI-related data across configuration changes.
How is ViewModel lifecycle-aware?
When its lifecycle owner is destroyed, it cleans up its data.
How does ViewModel help with application architecture?
It helps separate business logic from the View.
How does each UI component manage its ViewModel internally?
Each UI component, like an activity or fragment, has a ViewModelStore that stores its ViewModels.
Is it possible to force GC?
No, it just makes a request to the system, but it doesn’t guarantee that it will happen
What does launch mode define in Android?
Launch mode defines how an activity is launched.
What happens when the launch mode is set to SingleTask in Android?
If the activity already exists in the stack, it reuses it instead of creating a new one, and any activities above it in the stack are destroyed.
What is called when an activity is reused in SingleTask launch mode in Android?
Once the activity is reused, the onNewIntent method is called.
Why can’t a Fragment have constructor parameters in Android?
Because Android uses reflection to instantiate a Fragment with a no-argument constructor.
Why does setContentView need to be called in onCreate in Android?
Since setContentView is costly, it should be placed in onCreate() which is called only once during the activity lifecycle.
What causes App Lag?
- Frequent Garbage Collection (GC)
- Too much work being done on the main thread
What are the solutions to reduce App Lag?
- Use lazy initialization to defer initialization until needed
- Declare commonly used variables as static to prevent memory allocation overhead
- Move time-consuming tasks to a background thread
What’s Context in Android?
It provides access to app resources, system services, and environment information.
What’s ApplicationContext in Android?
- It’s tied to the app lifecycle and remains alive as long as the app is running.
- Use it when you need a long-lived context.
- Use the Activity context when you want to perform UI operations.
How to communicate between two Fragments?
- Both fragments share the same ViewModel.
- The hosting activity acts as a mediator to pass data.
What’s the retained Fragment in Android?
The fragment persists across configuration changes by calling setRetainInstance(true).
What’s the purpose of addToBackStack in Android?
- It’s used to add a transaction to the back stack, enabling the reversal of the transaction.
- Allows the user to return to the previous fragment when pressing the back button.
What’s the difference between View and ViewGroup in Android?
- View: A single UI element that displays content and interacts with the user.
- ViewGroup: A container that holds multiple Views and other ViewGroups.
What is the key performance advantage of SurfaceView over TextureView?
SurfaceView runs on a background thread, offering better performance than TextureView.
How does SurfaceView render content on the screen?
SurfaceView renders on a separate surface and overlays the main UI.
What is the key feature of TextureView regarding content transformations?
TextureView supports content transformations such as moving, resizing, and rotating.
On which thread does TextureView run?
TextureView runs on the main thread.
What is RecyclerView used for?
RecyclerView is an efficient view for displaying a large dataset.
How does RecyclerView improve performance?
RecyclerView improves performance by reusing the views that are no longer visible on the screen.
How can you improve RecyclerView performance by managing work in onBindViewHolder?
To improve performance, do not do too much work in onBindViewHolder.
Instead of using notifyDataSetChanged, what method should you use for specific changes to minimize unnecessary layout refreshes?
Use notifyItemChanged for specific changes to minimize unnecessary layout refreshes.
How can you reuse the original ViewHolder even when the data position changes?
Use setStableIds and override getItemId in the adapter to reuse the original ViewHolder.
When should you use setHasFixedSize in RecyclerView?
Use setHasFixedSize if the layout size doesn’t change when the data set is updated to skip unnecessary layout recalculations.
What is DiffUtil used for in RecyclerView?
DiffUtil is used to calculate the difference between two datasets, offering better performance for RecyclerView updates with minimal changes.
What is the main difference between Service and IntentService in terms of task execution?
A Service runs the task on the main thread, which can block the thread, while an IntentService runs the task on a background thread, making it more efficient for time-consuming tasks.
How is a Service stopped?
A Service needs to be manually stopped by calling stopService or stopItself.
How is an IntentService triggered and when does it stop?
An IntentService is triggered via an intent and automatically stops itself after the task completes.
Can tasks in an IntentService run in parallel?
No, tasks in an IntentService cannot run in parallel because each task is enqueued to the message queue of the worker thread and processed sequentially.
What does an explicit intent specify?
An explicit intent specifies which component should handle the intent.
What does an implicit intent specify?
An implicit intent specifies an action, and the OS decides which components can handle the intent.
What is the purpose of a ContentProvider?
A ContentProvider provides a way to expose data to other apps.
How can other apps interact with the data exposed by a ContentProvider?
Other apps can use ContentResolver to interact with the exposed data via a URI.
What is the purpose of ContentResolver?
ContentResolver is used to interact with data exposed by ContentProvider via a URI.
What causes an ANR (Application Not Responding)?
ANR occurs when too much work is being done on the main thread, causing it to be blocked and unresponsive to user interactions.
How can you avoid an ANR?
To avoid an ANR, move time-consuming tasks to background threads, making the main thread free to respond to user interactions.
What is the role of a Handler?
A Handler acts as a mediator to communicate between threads, allowing messages to be passed from one thread to another.
What three elements work with a Handler?
The three elements that work with a Handler are:
- MessageQueue – stores messages that need to be processed
- Looper – continuously retrieves and processes messages from MessageQueue
- Each thread has one looper, and each looper contains one MessageQueue.
How does a Handler work internally?
The Handler is tied to the looper of the thread that we want to communicate with and sends the message to the corresponding message queue. The looper continuously retrieves messages from the message queue and executes them on the corresponding thread.
When should you use a Handler?
Use a Handler to:
- Post UI updates to the main thread after a task completes on a background thread
- Schedule delayed or repeated tasks
What is a memory leak?
A memory leak occurs when an object is no longer needed but is still referenced, preventing it from being garbage collected.
How can you detect a memory leak in Android?
You can detect a memory leak using Android Studio Profiler or LeakCanary.
How can you prevent memory leaks?
To prevent memory leaks:
- Use weak references instead of strong references, as weak references should not prevent garbage collection
- Use ApplicationContext instead of ActivityContext for non-UI operations
- Properly remove callbacks and listeners in onDestroy
- Use lifecycle-aware components that automatically clean up when the lifecycle ends
What is garbage collection?
Garbage collection is a process that frees up memory by removing objects that are no longer needed.
What does OOM (Out of Memory) mean?
OOM occurs when an app exceeds its memory limit, causing an OOM exception to be thrown.
How can you prevent an OOM exception?
To prevent an OOM exception, optimize bitmap usage and avoid memory leaks to reduce the possibility of running out of memory.
How can you reduce memory usage when dealing with frequently accessed data?
Use caches for frequently accessed data.
How can you reduce memory usage when working with images?
Reduce image size by using inSampleSize.
How can you optimize memory usage with bitmaps?
Reuse bitmaps through bitmap pools.
What is a WeakReference?
A WeakReference is a reference that doesn’t prevent the referenced object from being garbage collected.
How does a WeakReference work internally?
If an object has strong references, it can’t be garbage collected even if it’s no longer used. If an object has only weak references, it can be garbage collected.
What is DataStore used for?
DataStore is used to asynchronously store lightweight data.
How does DataStore differ from SharedPreferences?
Unlike SharedPreferences, DataStore is type-safe, provides many asynchronous APIs for reading and writing data, and allows you to observe changes using Flow or LiveData.
What is Preference DataStore used for?
Preference DataStore is designed for key-value storage, similar to SharedPreferences. It uses type-safe keys to define data keys and supports common types like Int, Double, String, etc.
What is Proto DataStore used for?
Proto DataStore is designed for storing complex data structures using Protocol Buffers, which requires a defined schema. Protocol Buffers provide efficient serialization.
What is the difference between commit and apply in SharedPreferences?
- commit is a synchronous operation and blocks the thread until the operation completes. It returns a boolean value indicating whether the operation was successful.
- apply is an asynchronous operation and doesn’t return any results.
What is ORM (Object-Relational Mapping)?
ORM is a technique where each database table corresponds to a class, allowing interaction with the database using objects instead of SQL queries, making operations simpler.
Can you give an example of an ORM framework?
An example of an ORM framework is Room.
What is ComponentCallback2 used for?
ComponentCallback2 is used to receive memory-related callbacks, such as onTrimMemory, helping the app handle low memory situations.
What is NDK (Native Development Kit)?
NDK is a tool that allows developers to write native code (C/C++) and integrate it with Java/Kotlin using JNI (Java Native Interface).
What is an advantage of using native code in NDK?
Native code is compiled into machine code, bypassing ART (Android Runtime) for better performance.
What memory management feature does NDK provide?
NDK provides manual memory management, allowing developers more control over memory allocation.
What is the first step in converting Java/Kotlin code to running on a device?
The compiler converts Java/Kotlin code into bytecode.
What tools optimize and shrink the code after it’s converted into bytecode?
Proguard or R8 optimizes and shrinks the code.
After bytecode is optimized, what happens next?
Android build tools transform the bytecode into multiple .dex files.
What happens after the .dex files, resources, and native libraries are created?
The .dex files, resources, and native libraries are bundled into an APK or AAB.
How does Android OS run the code on a device?
Android OS uses ART (Android Runtime) to convert .dex files into machine code and then runs it on the device.
Why are ART and Dalvik needed in Android?
Devices can’t run bytecode directly, so it needs to be converted to machine code.
How is bytecode converted to machine code in Android?
The conversion is handled by ART (Android Runtime) or Dalvik, depending on the Android version.
What is JIT (Just-in-Time) compilation?
JIT is a process where bytecode is converted into machine code at runtime, meaning only the code that is actually executed gets compiled.
How does JIT improve performance?
Frequently used code is cached, helping avoid re-compiling it again.
What is AOT (Ahead-of-Time) compilation?
AOT is a process where bytecode is converted into machine code before the app is executed.
How does AOT improve app performance?
AOT allows the app to run more efficiently because the conversion from bytecode to machine code has already been done in advance.
What is Dalvik in Android?
Dalvik is a runtime that uses JIT (Just-in-Time) compilation to convert bytecode into machine code at runtime.
What is an advantage of Dalvik?
Dalvik has a smaller APK size and faster installation time.
What is a disadvantage of Dalvik?
Dalvik has lower performance and a longer startup time compared to newer runtimes.
What is ART (Android Runtime)?
ART is a runtime that uses AOT (Ahead-of-Time) compilation to convert bytecode into machine code before the app is executed.
What is an advantage of ART?
ART has higher performance and a shorter startup time compared to Dalvik.
What is a disadvantage of ART?
ART has a larger APK size and longer installation time compared to Dalvik.
What is Profile-guided optimization?
Profile-guided optimization collects runtime data to identify the most frequently used code to precompile, improving runtime performance.
How does Profile-guided optimization affect app performance over time?
Initially, the app may run slowly, but it will become faster over time as the frequently used code is precompiled.
What is ART Cloud Profile?
ART Cloud Profile collects runtime data from other devices to precompile, improving the initial performance of the app.
What is Baseline Profile?
A Baseline Profile is a file created by developers that identifies the most frequently used code to precompile, reducing startup time and improving runtime performance.
How is the Baseline Profile used?
The Baseline Profile file will be uploaded with the APK or AAB to ensure faster startup and improved performance.
What is Jetpack?
Jetpack is a collection of Android libraries designed to streamline app development, including components like ViewModel, LiveData, and Compose.
What is LiveData?
LiveData is an observable data holder that respects the lifecycle of its observers.
How does LiveData ensure UI updates are lifecycle-aware?
LiveData ensures that UI updates are lifecycle-aware, meaning observers are notified only when they are in an active state.
Is LiveData thread-safe?
Yes, LiveData is thread-safe, ensuring that observers are notified on the main thread.
How does LiveData prevent memory leaks?
LiveData automatically cleans up when the lifecycle is destroyed, preventing memory leaks.
What is the difference between setValue and postValue in LiveData?
- setValue must be called on the main thread, updates the value synchronously, and notifies observers immediately.
- postValue can be called from any thread, updates the value asynchronously, and posts it to the main thread’s message queue, meaning the update may be delayed.
What is the key difference between LiveData and StateFlow in terms of lifecycle awareness?
LiveData is lifecycle-aware, while StateFlow can be made lifecycle-aware using repeatOnLifecycle.
How do LiveData and StateFlow differ in terms of requiring an initial value?
StateFlow requires an initial value, whereas LiveData does not.
How do LiveData and StateFlow differ in terms of thread notification?
LiveData’s observers are notified on the main thread, whereas StateFlow’s collectors are notified on the thread where the flow is collected.
What is WorkManager used for?
WorkManager is used to schedule and execute background tasks even when the app is not running.
What features does WorkManager support?
WorkManager supports constraints such as network connectivity, battery status, and can chain multiple tasks to run sequentially or in parallel.
What is Serialization?
Serialization is the process of converting an object into a format that can be easily stored and transmitted.
What is Deserialization?
Deserialization is the process of converting serialized data back into its original object form.
What is the difference between Parcelable and Serializable in terms of platform?
Parcelable is an Android-specific interface, while Serializable is a Java interface.
Why is Parcelable faster than Serializable?
Parcelable is faster because it avoids reflection when serializing objects (Parcelable implements custom conversion functions), whereas Serializable creates more temporary objects due to reflection.
How do Parcelable and Serializable differ in terms of implementation complexity?
Serializable is simpler to implement, while Android Studio provides a plugin to streamline the setup of Parcelable.
What is the key difference between Gson and Jackson in terms of performance?
Jackson offers better performance compared to Gson.
What additional features does Jackson provide?
Jackson provides additional features such as the streaming API.
How do Gson and Jackson differ in terms of ease of use?
Gson is simpler to use as it requires less code and configuration compared to Jackson.
What is an Interceptor used for in network requests?
An Interceptor is used to intercept, modify, and retry network requests and responses.
What does addInterceptor do?
addInterceptor operates at the application level, modifying requests before they are sent to the server. It’s commonly used for adding custom headers, authentication tokens, logging, and response caching.
What does addNetworkInterceptor do?
addNetworkInterceptor operates at the network level and is commonly used for handling redirections, retries, and tracking request progress.
What is Hilt?
Hilt is a Dependency Injection (DI) framework built on Dagger.
How does Hilt generate code?
Hilt uses annotations to generate code at compile time, ensuring safe and efficient dependency injection.
How does Hilt help prevent memory leaks?
Hilt scopes dependencies to the lifecycle of Android components, preventing memory leaks.
What is Koin?
Koin is a lightweight Dependency Injection (DI) framework designed for Kotlin.
How does Koin resolve dependencies?
Koin resolves dependencies at runtime using a Service Locator pattern.
How does Koin improve the implementation and readability of dependency injection?
Koin uses Kotlin DSL to define dependency modules, making the implementation easier and improving readability.
How does Hilt and Koin differ in terms of dependency resolution?
- Hilt uses annotations to generate dependencies at compile time.
- Koin uses Kotlin DSL to define dependency modules and resolves them at runtime.
Which framework is more lightweight, Hilt or Koin?
Koin is more lightweight as it doesn’t generate extra code.
Which framework is safer in terms of dependency resolution, Hilt or Koin?
Hilt is safer since dependencies are resolved at compile time.
What is a Module in Hilt?
A module provides dependency definitions in Hilt.
What does a Component determine in Hilt?
A component determines the lifecycle of dependencies. Examples include SingletonComponent and ActivityComponent.
What is the role of a Scope in Hilt?
A scope ensures dependencies persist as long as the associated component is alive. If no scope is specified, each request gets a new instance.
How must the scope of a dependency match in Hilt?
The scope of a dependency must match the scope of the component. For example, a dependency within ActivityComponent must be ActivityScoped.
What are some examples of scopes in Hilt?
Examples of scopes in Hilt include @Singleton and @ActivityRetainedScope
What is the purpose of @Provides in Hilt?
@Provides is used when a dependency needs to be created using a constructor or factory method.
What is the purpose of @Binds in Hilt?
@Binds is used to bind an interface or abstract class to its implementation.
What is an EntryPoint in Hilt?
An EntryPoint acts as a bridge to inject dependencies into classes that Hilt doesn’t support.
What is @AndroidEntryPoint in Hilt?
@AndroidEntryPoint is used to simplify dependency injection for Android components. Hilt automatically generates an abstract base class which the component extends to handle injection, allowing the component to receive dependencies without manual setup.
What is inBitmap in Android?
inBitmap is an option that allows reusing an existing bitmap when decoding a new image, helping to reduce memory allocations.
What are the limits of using inBitmap?
- The reused bitmap must be mutable.
- Its size must be equal to or larger than the size of the decoded image.
- If these conditions aren’t met, a new bitmap is created.
What must be used with inBitmap?
inBitmap must be used with inMutable.
What is bitmap pooling?
Bitmap pooling is used to prevent frequent memory allocation by reusing bitmaps
How can you use bitmap pooling?
You can set BitmapFactory.Options inBitmap or use a third-party bitmap pool to access bitmaps.
How can you customize a bitmap pool?
You can customize the bitmap pool by using LruCache to manage the storage of bitmaps.
How does Glide use caching?
Glide uses two levels of caching:
- Memory Caching: It uses LruCache to store images in memory, allowing quick access and reducing the overhead of decoding.
- Disk Caching: It is split into original and transformed caches, both using DiskLruCache to store images on disk.
How does Glide handle bitmap reuse?
Glide reuses bitmaps using a bitmap pool, which helps reduce frequent memory allocations.
How is Glide lifecycle-aware?
Glide is lifecycle-aware by creating a hidden Fragment that attaches to the context and automatically cancels image requests when the context’s lifecycle is destroyed.
How does Glide optimize memory usage?
Glide automatically downsamples images to optimize memory usage.
What is MVC in Android?
Model-View-Controller (MVC) is an architectural pattern where:
- Activity acts as both View and Controller, violating the single responsibility principle.
- As complexity increases, maintaining the Activity becomes difficult.
What is MVP in Android?
Model-View-Presenter (MVP) is an architectural pattern where:
- The Presenter communicates with View using an interface, which is usually implemented by the View itself.
- The Presenter holds a reference to the View, which can lead to memory leaks.
- As complexity increases, the interface grows larger, leading to stronger coupling between View and Presenter.
What is MVVM in Android?
Model-View-ViewModel (MVVM) is an architectural pattern where:
- The View observes changes in observable data provided by the ViewModel to update the UI.
- It reduces coupling and separates business logic from the View.
How does the View interact with the ViewModel in MVVM?
The View directly interacts with the ViewModel by calling its methods to update the state.
What is a downside of MVVM?
As complexity increases, state management becomes difficult, reducing flexibility.
What is MVI in Android?
Model-View-Intent (MVI) is an architectural pattern where:
- Intent represents user actions that the View sends to ViewModel to trigger a state change.
- It follows Unidirectional Data Flow, making state management more predictable.
What is the main advantage of MVI?
Unidirectional Data Flow makes state management more predictable and easier to debug.
What is the downside of MVI?
It requires more boilerplate code to define actions.
How does the View interact with the ViewModel in MVVM vs. MVI?
- MVVM: View directly calls ViewModel methods.
- MVI: View sends an Intent to ViewModel, making it unaware of ViewModel internals.
How does state management differ between MVVM and MVI?
- MVVM: State management can become difficult as complexity increases.
- MVI: Unidirectional Data Flow makes state management more predictable.
What is the main downside of MVI?
More boilerplate code is required to define actions.
What is the difference between TestRule and TestWatcher?
- TestRule is more flexible, allowing custom behavior for tests, such as modifying test execution conditions.
- TestWatcher extends TestRule and provides default implementations for lifecycle methods like starting() and finished(), making it easier and more commonly used.
What’s the advantage of using TestRule?
It offers customizable behavior and allows modifying how tests are executed, giving more control over the test process.
Why is TestWatcher commonly used?
TestWatcher is easier to implement since it provides default lifecycle method implementations that handle common test events, reducing boilerplate code.
What is InstantTaskExecutorRule?
It replaces the default background executor, forcing LiveData and other background operations to execute synchronously on the test thread, ensuring LiveData updates are immediate and tests are predictable.
Why is InstantTaskExecutorRule useful in testing?
It helps ensure that LiveData updates happen immediately and synchronously, making tests more reliable and predictable by avoiding asynchronous behavior.
When should you use InstantTaskExecutorRule?
It’s commonly used in unit tests involving LiveData or other background tasks to prevent timing issues that could arise from asynchronous execution.
What is Robolectric?
It allows Android tests to run on JVM without needing an emulator or physical device by simulating the Android environment, making test execution faster but less reliable.
What’s the advantage of using Robolectric for testing?
It makes test execution faster by running on JVM, avoiding the need for an emulator or physical device, which is especially useful for unit tests.
What’s the drawback of using Robolectric?
While faster, it may be less reliable than real device or emulator testing because it simulates the Android environment, and some features may not behave exactly the same way as they would on an actual device.
What is a Unit Test?
A unit test focuses on testing small parts of code, such as functions and classes, in isolation, typically without the need for an actual Android device or emulator.
What is an Instrumented Test?
An instrumented test focuses on testing real Android components to ensure they work correctly on an Android device or emulator.
What’s the main difference between Unit Test and Instrumented Test?
- Unit Test tests individual code components in isolation without relying on a device or emulator.
- Instrumented Test tests the actual Android components (like activities or services) on a real device or emulator.
What is Code Coverage?
Code coverage measures the percentage of the codebase that is executed during testing, indicating how thoroughly the code has been tested.
Why is Code Coverage important?
Code coverage helps identify untested parts of the code, ensuring that tests are thorough and improving the reliability of the application by detecting potential issues.
What does a high Code Coverage indicate?
A high code coverage indicates that a large portion of the code has been tested, but it doesn’t necessarily mean the tests are comprehensive or effective.
What is ADB?
ADB (Android Debug Bridge) is a command-line tool that allows you to interact with Android devices for tasks like installation, debugging, and management.
What does the command adb devices do?
The command adb devices lists all devices connected to the computer, showing which Android devices are available for interaction.
What does the command adb install <path-to-apk> do?</path-to-apk>
The command adb install <path-to-apk> installs an APK on a connected Android device from the specified file path.</path-to-apk>
What is Strict Mode?
Strict Mode is a debugging tool that helps developers detect performance issues, such as when the main thread is blocked or when disk/network operations are performed on the main thread.
How does Strict Mode help developers?
Strict Mode provides a dialog or log to display performance issues, helping developers identify and fix problematic code that can impact app performance.
What types of issues can Strict Mode detect?
Strict Mode can detect issues like main thread blocking, disk access or network operations happening on the main thread, and slow database queries.
What is Lint?
Lint is a code analysis tool that helps developers detect potential issues in the code, such as code style violations, performance problems, or incorrect usage of Android APIs.
How can you create a custom Lint rule?
To create a custom Lint rule:
- Add dependencies for Lint in the project.
- Create a class that extends Detector() and implements SourceCodeScanner to define the rule.
- Create an issue object that defines the rule details.
- Create a repository that extends IssueRegistry() to register the rule.
What is the purpose of creating custom Lint rules?
Custom Lint rules help developers enforce specific coding standards or best practices in their codebase and identify issues unique to their project that the default Lint rules may not catch.
What are Proguard and R8?
Proguard and R8 are tools used to optimize, obfuscate, and shrink the app’s code to make it more secure, smaller, and performant.
What does code obfuscation do?
Code obfuscation makes the code harder to reverse-engineer by renaming classes, methods, and variables to meaningless names, making it more difficult for someone to understand or modify the code.
What is the purpose of code shrinking?
Code shrinking reduces the size of the app by removing unused code and resources, which helps to reduce the APK size and improve performance.
What’s the main difference between Proguard and R8?
R8 has replaced Proguard as the default tool for code shrinking, obfuscation, and optimization in Android.
Why is R8 faster than Proguard?
R8 is faster because it integrates the dexing process, streamlining the build process, whereas Proguard works separately from dexing.
How does the size of the app created by R8 compare to Proguard?
The size of the app created by R8 is smaller than that created by Proguard due to its better algorithm for code shrinking and optimization.
Is R8 enabled by default?
Yes, R8 is enabled by default in Android projects, and it automatically replaces Proguard.
Who maintains R8?
R8 is maintained by Google, and it is integrated into the Android build tools.
How can you reduce APK size using R8?
Use R8 to shrink the APK size by removing unused code and resources and optimizing the remaining code.
Why should you switch to AAB (Android App Bundles)?
Switching to AAB allows optimized APKs to be generated for different devices, which reduces the overall APK size by serving only the resources required for the specific device.
How can vector drawables help reduce APK size?
Vector drawables are scalable and lightweight compared to PNGs, making them a more efficient choice for reducing image size in the APK.
What is the role of ABI in reducing APK size?
By using ABI (Application Binary Interface), you can separate binary code for different OS platforms (like ARM, x86), ensuring that only the necessary binaries for each platform are included in the APK.
What is ABI (Application Binary Interface) and how does it reduce APK size?
ABI defines how binary files interact with the OS and platform. By using ABI, you can ensure the app includes only the necessary code for the target device, reducing the size of the APK by excluding unnecessary binaries for other platforms.
How can you speed up the Gradle build process?
- Enable parallel execution: Run tasks in parallel to speed up the process.
- Use the build cache: Cache outputs of tasks to avoid re-execution.
- Remove unnecessary dependencies: Minimize the dependencies in your project to avoid unnecessary processing.
What is ThreadPoolExecutor?
It’s an efficient utility for managing and reusing threads, enabling concurrent execution of tasks. A thread pool maintains a collection of reusable threads, reducing the overhead of thread creation.
How does ThreadPoolExecutor work when a task is submitted?
- If the number of threads is less than the core pool size, a new thread is created.
- If core threads are busy, the task is added to the queue.
- If the queue is full and the number of threads is less than the max pool size, a new thread is created.
- If the queue is full and the max pool size is reached, the task is rejected.
What is Write-Ahead Logging (WAL)?
Write-Ahead Logging is a technique where changes to the database are first written to a log file before being applied to the database.
How does Write-Ahead Logging (WAL) work during a checkpoint?
As the log file reaches a checkpoint, all updates are committed to the database.
What are the benefits of Write-Ahead Logging (WAL)?
- Ensures data integrity and allows recovery in case of an error.
- Improves performance because appending every change to a log file is faster than directly modifying the database.
What is the transient modifier used for?
It’s used to indicate that a field should not be serialized, meaning it will be excluded in the serialized form.
Why would you use the transient modifier?
It’s used for fields that contain sensitive or unnecessary data that you don’t want to persist.
What happens to a transient field after deserialization?
The field is set to its default value, and if the field is a non-null object type, accessing it may throw an exception.
How can you avoid API keys from being checked into version control (VCS)?
Store the key in a gradle.properties file, read the value from the file, and add it to BuildConfig in build.gradle.
How do you access the API key in your code after adding it to BuildConfig?
Access the value using BuildConfig in your code.
What should you do with the gradle.properties file to prevent it from being committed to VCS?
Exclude the gradle.properties file from version control by adding it to .gitignore.
What are the three stages of event dispatch in Android View?
The three stages are:
- dispatchTouchEvent
- onInterceptTouchEvent
- onTouchEvent
What is the purpose of dispatchTouchEvent in Android event dispatch?
dispatchTouchEvent is the entry point for events and returns whether the event is consumed by itself or its children.
What happens in the onInterceptTouchEvent stage of event dispatch?
onInterceptTouchEvent determines whether the event should be intercepted. If intercepted, the event won’t be propagated further, and onTouchEvent is called.
What does onTouchEvent do in the event dispatch process?
onTouchEvent determines whether the event is consumed. If not, the event is propagated to the next view.
Which methods are available in ViewGroup but not in View?
ViewGroup contains all three methods (dispatchTouchEvent, onInterceptTouchEvent, onTouchEvent), but View doesn’t have onInterceptTouchEvent.
What determines whether a complete event sequence is received?
It depends on whether the TOUCH_DOWN event is consumed.
What happens if a ViewGroup intercepts TOUCH_DOWN?
If TOUCH_DOWN is intercepted, subsequent events will bypass onInterceptTouchEvent and go directly to onTouchEvent.
What happens if TOUCH_DOWN is not consumed in onTouchEvent?
If TOUCH_DOWN is not consumed, subsequent events will bypass the View or ViewGroup.
What will happen if a view event is not consumed by Views and ViewGroups?
If the event is not consumed by Views and ViewGroups, it will be handled by the activity.
What ensures thread safety when processing messages in a Handler?
MessageQueue uses a synchronization mechanism to ensure thread safety while processing messages.
How does LeakCanary detect memory leaks internally?
LeakCanary detects memory leaks using a WeakReference with a ReferenceQueue.
What happens when an object becomes unreachable in LeakCanary?
When an object becomes unreachable, the WeakReference is added to the ReferenceQueue.
How does LeakCanary determine if a memory leak has occurred?
LeakCanary checks the ReferenceQueue. If the WeakReference appears, it indicates that a leak has occurred
What does requestLayout do in Android?
requestLayout triggers onMeasure() and onLayout, but it doesn’t execute onDraw() unless the View’s position or size changes.
What does invalidate do in Android?
invalidate triggers onDraw(), allowing the view to be redrawn.
What are the four Launch Modes in Android?
The four launch modes are:
- standard
- singleTop
- singleTask
- singleInstance
What does the standard launch mode do?
standard creates a new activity instance in the current stack.
What does the singleTop launch mode do?
singleTop creates a new activity instance only when the top of the current stack is not the activity instance; otherwise, the onNewIntent() method is called.
What does the singleTask launch mode do?
singleTask creates a new activity instance only when there is no activity instance in the current stack; otherwise, the onNewIntent() method is called and other activity instances above it in the stack are destroyed.
What does the singleInstance launch mode do?
singleInstance creates a new activity instance in a new stack.
What is Clean Architecture?
Clean Architecture splits an app into three layers—Data, Domain, and Presentation—to improve flexibility and testability by minimizing dependencies between layers.
What are the three layers of Clean Architecture?
- Data – Handles data sources like databases and APIs.
- Domain – Contains business logic and use cases.
- Presentation – Manages UI and user interactions.
How does Clean Architecture improve maintainability?
By ensuring that changes in one layer minimally affect others, making the code more modular and easier to test.
What tools and patterns are commonly used with Clean Architecture?
Dependency injection frameworks like Hilt or Koin, and UI patterns like MVVM or MVI.
What is Paging in Android?
Paging is designed to load data in small chunks rather than all at once, reducing memory usage and network overhead.
What are the components of Paging?
The components of Paging are:
- PagingSource
- Pager
- PagingDataAdapter
What is PagingSource used for?
PagingSource is used to load data based on the page number and page size, returning the results to the Paging stream.
What does Pager do in Paging?
Pager ties everything together and is used to provide a stream of PagingData.
What is the role of PagingDataAdapter?
PagingDataAdapter connects to RecyclerView with the PagingData stream and uses DiffUtil to minimize changes and optimize updates.