All topics

Android interview questions

122 questions with answers. 398 open jobs in India ask for Android.

  1. Explain: -nodpi, -anydpi qualifiers for resources

    From the Google-android source code

    nodpi: Fallback

    • A drawable inside the res/drawable-nodpi/ folder is valid for any screen density. Eg. drawable-nodpi/ic_icon.png The above icon will will look small on xxxhdpi devices and big on ldpi devices.

      drawable-hdpi/ic_icon.png drawable-nodpi-21/ic_icon.xml In android 21 hdpi devices ic_icon.png will be used and in android 21 xhdpi devices ic_icon.xml will be used.

    anydpi: Takeover

    • A drawable inside drawable-anydpi is also valid for any screen density but anydpi variant has more priority over any density specific variant.

      Eg. If we have res/drawable-anydpi/ic_icon.xml and res/drawable-xxxhdpi/ic_icon.png then ic_icon.xml will be used even in xxxhdpi devices.

      -Most of the times -anydpi used in conjunction with other qualifiers. A good example is anydpi-v21 as vector drawables were introduced in android 21 , so after that we usually have res/drawable-anydpi-v21/ic_icon.xml (Vector drawable) and res/drawable-xxhdpi/ic_icon.png. The vector drawable (ic_icon.xml) will be used in all android 21+ devices and ic_icon.png will be used in xxhdpi devices runing in android 4.4 or older

    From Android Interview Questions (Apache 2.0)

  2. Explain: Activity Lifecycle

    Activity Lifecycle

    As a user navigates through, out of, and back to your app, the Activity instances in your app transition through different states in their lifecycle. The Activity class provides a number of callbacks that allow the activity to know that a state has changed: that the system is creating, stopping, or resuming an activity, or destroying the process in which the activity resides.

    To navigate transitions between stages of the activity lifecycle, the Activity class provides a core set of six callbacks: onCreate(), onStart(), onResume(), onPause(), onStop(), and onDestroy(). The system invokes each of these callbacks as an activity enters a new state.

    As the user begins to leave the activity, the system calls methods to dismantle the activity. In some cases, this dismantlement is only partial; the activity still resides in memory (such as when the user switches to another app), and can still come back to the foreground. If the user returns to that activity, the activity resumes from where the user left off.

    onCreate()

    You must implement this callback, which fires when the system first creates the activity. On activity creation, the activity enters the Created state. In the onCreate() method, you perform basic application startup logic that should happen only once for the entire life of the activity. For example, your implementation of onCreate() might bind data to lists, associate the activity with a ViewModel, and instantiate some class-scope variables. This method receives the parameter savedInstanceState, which is a Bundle object containing the activity's previously saved state. If the activity has never existed before, the value of the Bundle object is null.

    If you have a lifecycle-aware component that is hooked up to the lifecycle of your activity it will receive the ON_CREATE event. The method annotated with @OnLifecycleEvent will be called so your lifecycle-aware component can perform any setup code it needs for the created state.

    Your activity does not reside in the Created state. After the onCreate() method finishes execution, the activity enters the Started state, and the system calls the onStart() and onResume() methods in quick succession.

    onStart()

    When the activity enters the Started state, the system invokes this callback. The onStart() call makes the activity visible to the user, as the app prepares for the activity to enter the foreground and become interactive. For example, this method is where the app initializes the code that maintains the UI.

    When the activity moves to the started state, any lifecycle-aware component tied to the activity's lifecycle will receive the ON_START event.

    The onStart() method completes very quickly and, as with the Created state, the activity does not stay resident in the Started state. Once this callback finishes, the activity enters the Resumed state, and the system invokes the onResume() method.

    onResume()

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  3. Build Type, Product Flavor, Build Variant

    Build Type, Product Flavor, Build Variant

    Build Type

    Build Types controls how to build and package your app, for example whether or not ProGuard is run, how the resulting application package is signed and whether debug symbols are to be included. By default, the build system defines two build types: debug and release.

    Product Flavor

    Product Flavor configuration defines a customized version of the application build. It can be used to specify custom features, minimum and target API levels, device and API requirements like layout, drawable and custom code. This can help create different label apps as well. Flavours can vary in adding different features or customizing exisitng features, different icons and resources, different styles and strings etc.

    Build Variant

    The combination of Build Type and Product Flavor is known as Build Variant. For example, for above build types (debug and release) and product flavours (demo and full versions), build variants can be: demoDebug, demoRelease, fullDebug, fullRelease.

    Links

    https://developer.android.com/studio/build/build-variants
    https://wajahatkarim.com/2018/04/difference-between-build-type-flavour-and-build-variant-in-android/
    https://stackoverflow.com/questions/27905934/why-are-build-types-distinct-from-product-flavors

    From Android Interview Questions (Apache 2.0)

  4. Describe Fragment lifecycle

    Fragment Lifecycle

    Each Fragment instance has its own lifecycle. When a user navigates and interacts with your app, your fragments transition through various states in their lifecycle as they are added, removed, and enter or exit the screen.

    To manage lifecycle, Fragment implements LifecycleOwner, exposing a Lifecycle object that you can access through the getLifecycle() method.

    Each possible Lifecycle state is represented in the Lifecycle.State enum1:

    • INITIALIZED
    • CREATED
    • STARTED
    • RESUMED
    • DESTROYED

    As an alternative to using a LifecycleObserver, the Fragment class includes callback methods that correspond to each of the changes in a fragment's lifecycle. These include onCreate(), onStart(), onResume(), onPause(), onStop(), and onDestroy().

    A fragment's view has a separate Lifecycle that is managed independently from that of the fragment's Lifecycle. Fragments maintain a LifecycleOwner for their view, which can be accessed using getViewLifecycleOwner() or getViewLifecycleOwnerLiveData(). Having access to the view's Lifecycle is useful for situations where a Lifecycle-aware component should only perform work while a fragment's view exists, such as observing LiveData that is only meant to be displayed on the screen.2

    Fragment lifecycle states and callbacks

    Image below shows ach of the fragment's Lifecycle states and how they relate to both the fragment's lifecycle callbacks and the fragment's view Lifecycle:

    As a fragment progresses through its lifecycle, it moves upward and downward through its states. For example, a fragment that is added to the top of the back stack moves upward from CREATED to STARTED to RESUMED. Conversely, when a fragment is popped off of the back stack, it moves downward through those states, going from RESUMED to STARTED to CREATED and finally DESTROYED.

    When moving upward through its lifecycle states, a fragment first calls the associated lifecycle callback for its new state. Once this callback is finished, the relevant Lifecycle.Event is emitted to observers by the fragment's Lifecycle, followed by the fragment's view Lifecycle, if it has been instantiated.

    Fragment CREATED

    When your fragment reaches the CREATED state, it has been added to a FragmentManager and the onAttach() method has already been called.

    This would be the appropriate place to restore any saved state associated with the fragment itself through the fragment's SavedStateRegistry. Note that the fragment's view has not been created at this time, and any state associated with the fragment's view should be restored only after the view has been created.

    This transition invokes the onCreate() callback. The callback also receives a savedInstanceState Bundle argument containing any state previously saved by onSaveInstanceState(). Note that savedInstanceState has a null value the first time the fragment is created, but it is always non-null for subsequent recreations, even if you do not override onSaveInstanceState().

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  5. Describe android modularization in general

    Android modularization

    A project with multiple Gradle modules is known as a multi-module project. In an ever-growing codebase, scalability, readability, and overall code quality often decrease through time. This comes as a result of the codebase increasing in size without its maintainers taking active measures to enforce a structure that is easily maintainable. Modularization is a means of structuring your codebase in a way that improves maintainability and helps avoid these problems.

    What is modularization?

    Modularization is a practice of organizing a codebase into loosely coupled and self contained parts. Each part is a module. Each module is independent and serves a clear purpose. By dividing a problem into smaller and easier to solve subproblems, you reduce the complexity of designing and maintaining a large system.

    Benefits of modularization

    Benefit Summary
    Reusability Modularization enables opportunities for code sharing and building multiple apps from the same foundation. Modules are effectively building blocks. Apps should be a sum of their features where the features are organized as separate modules. The functionality that a certain module provides may or may not be enabled in a particular app. For example, a :feature:news can be a part of the full version flavor and wear app but not part of the demo version flavor.
    Strict visibility control Modules enable you to easily control what you expose to other parts of your codebase. You can mark everything but your public interface as internal or private to prevent it from being used outside the module.
    Customizable delivery Play Feature Delivery uses the advanced capabilities of app bundles, allowing you to deliver certain features of your app conditionally or on demand.

    The benefits above are only achievable with a modularized codebase. The following benefits might be achieved with other techniques but modularization can help you enforce them even more.

    Benefit Summary
    Scalability In a tightly coupled codebase a single change can trigger a cascade of alterations in seemingly unrelated parts of code. A properly modularized project will embrace the separation of concerns principle and therefore limit the coupling. This empowers the contributors through greater autonomy.
    Ownership In addition to enabling autonomy, modules can also be used to enforce accountability. A module can have a dedicated owner who is responsible for maintaining the code, fixing bugs, adding tests, and reviewing changes.
    Encapsulation Encapsulation means that each part of your code should have the smallest possible amount of knowledge about other parts. Isolated code is easier to read and understand.
    Testability Testability characterizes how easy it is to test your code. A testable code is one where components can be easily tested in isolation.
    Build time Some Gradle functionalities such as incremental build, build cache or parallel build, can leverage modularity to improve build performance.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  6. Describe jetpack compose phases

    Jetpack Compose Phases

    Like most other UI toolkits, Compose renders a frame through several distinct phases. If we look at the Android View system, it has three main phases: measure, layout, and drawing. Compose is very similar but has an important additional phase called composition at the start.

    The three phases of a frame

    Compose has three main phases:

    • Composition: What UI to show. Compose runs composable functions and creates a description of your UI.
    • Layout: Where to place UI. This phase consists of two steps: measurement and placement. Layout elements measure and place themselves and any child elements in 2D coordinates, for each node in the layout tree.
    • Drawing: How it renders. UI elements draw into a Canvas, usually a device screen.

    The order of these phases is generally the same, allowing data to flow in one direction from composition to layout to drawing to produce a frame (also known as unidirectional data flow). BoxWithConstraints and LazyColumn and LazyRow are notable exceptions, where the composition of its children depends on the parent's layout phase.

    You can safely assume that these three phases happen virtually for every frame, but for the sake of performance, Compose avoids repeating work that would compute the same results from the same inputs in all of these phases. Compose skips running a composable function if it can reuse a former result, and Compose UI doesn't re-layout or re-draw the entire tree if it doesn't have to. Compose performs only the minimum amount of work required to update the UI. This optimization is possible because Compose tracks state reads within the different phases.

    State reads

    When you read the value of a snapshot state during one of the phases listed above, Compose automatically tracks what it was doing when the value was read. This tracking allows Compose to re-execute the reader when the state value changes, and is the basis of state observability in Compose.

    State is commonly created using mutableStateOf() and then accessed through one of two ways: by directly accessing the value property, or alternatively by using a Kotlin property delegate. You can read more about them in State in composables. For the purposes of this guide, a "state read" refers to either of those equivalent access methods.

    // State read without property delegate.
    val paddingState: MutableState<Dp> = remember { mutableStateOf(8.dp) }
    Text(
        text = "Hello",
        modifier = Modifier.padding(paddingState.value)
    )
    

    or

    // State read with property delegate.
    var padding: Dp by remember { mutableStateOf(8.dp) }
    Text(
        text = "Hello",
        modifier = Modifier.padding(padding)
    )
    

    Under the hood of the property delegate, "getter" and "setter" functions are used to access and update the State’s value. These getter and setter functions are only invoked when you reference the property as a value, and not when it is created, which is why the two ways above are equivalent.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  7. What is the difference between Room and SQLite?

    Room vs SQLite

    SQLite is an in-process library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine.

    SQLite is an embedded SQL database engine. Unlike most other SQL databases, SQLite does not have a separate server process. SQLite reads and writes directly to ordinary disk files. A complete SQL database with multiple tables, indices, triggers, and views, is contained in a single disk file. The database file format is cross-platform - you can freely copy a database between 32-bit and 64-bit systems or between big-endian and little-endian architectures

    The Room persistence library provides an abstraction layer over SQLite to allow for more robust database access while harnessing the full power of SQLite.

    The library helps you create a cache of your app's data on a device that's running your app. This cache, which serves as your app's single source of truth, allows users to view a consistent copy of key information within your app, regardless of whether users have an internet connection.

    Room is an ORM, Object Relational Mapping library. In other words, Room will map our database objects to Java objects. Room provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.

    Difference between SQLite and Room persistence library:

    • In the case of SQLite, There is no compile-time verification of raw SQLite queries. But in Room, there is SQL validation at compile time.
    • You need to use lots of boilerplate code to convert between SQL queries and Java data objects. But, Room maps our database objects to Java Object without boilerplate code.
    • As your schema changes, you need to update the affected SQL queries manually. Room solves this problem.
    • Room is built to work with LiveData and RxJava for data observation, while SQLite does not.

    Links

    https://medium.com/mindorks/using-room-database-android-jetpack-675a89a0e942
    https://developer.android.com/topic/libraries/architecture/room
    https://www.sqlite.org/about.html

    From Android Interview Questions (Apache 2.0)

  8. What is the difference between raw and assets folders?

    Raw folder vs Assets folder

    The files in both directories will be stored intact in the APK package after being packaged and will not be compiled into binary systems.

    The differences between res/raw and assets:

    Since raw is a subfolder of Resources (res), Android will automatically generate an ID for any file located inside it. This ID is then stored an the R class that will act as a reference to a file, meaning it can be easily accessed from other Android classes and methods and even in Android XML files. Using the automatically generated ID is the fastest way to have access to a file in Android.

    The Assets folder is an “appendix” directory. The R class does not generate IDs for the files placed there, so its less compatible with some Android classes and methods. Also, it’s much slower to access a file inside it, since you will need to get a handle to it based on a String. However some operations are more easily done by placing files in this folder, like copying a database file to the system’s memory. There’s no (easy) way to create an Android XML reference to files inside the Assets folder.

    Links

    https://developer.android.com/guide/topics/resources/providing-resources
    https://stackoverflow.com/questions/9563373/when-should-i-use-the-assets-as-opposed-to-raw-resources-in-android
    https://topic.alibabacloud.com/a/the-difference-between-the-asset-folder-and-the-raw-folder-in-android-deep-parsing-_android_1_21_20133424.html

    From Android Interview Questions (Apache 2.0)

  9. Explain: Different between @id and @+id

    @id vs @+id

    The at-symbol (@) at the beginning of the string indicates that the XML parser should parse and expand the rest of the ID string and identify it as an ID resource. The plus-symbol (+) means that this is a new resource name that must be created and added to our resources (in the R.java file). In other words, the + symbol tells Android build tools that you are declaring a new resource, @id/ you are referring to an existing resource (predefined by @+id/ and already exists in R.java.

    From Android Interview Questions (Apache 2.0)

  10. How does RecyclerView differ from ListView?

    With the advent of Android Lollipop, the RecyclerView made its way officially. The RecyclerView is much more powerful, flexible and a major enhancement over ListView.

    • ViewHolder Pattern In a ListView, it was recommended to use the ViewHolder pattern but it was never a compulsion. In case of RecyclerView, this is mandatory using the RecyclerView.ViewHolder class.

    • LayoutManager This is another massive enhancement brought to the RecyclerView. In a ListView, the only type of view available is the vertical ListView. There is no official way to even implement a horizontal ListView. Now using a RecyclerView, we can have a

      • LinearLayoutManager - which supports both vertical and horizontal lists,
      • StaggeredLayoutManager - which supports Pinterest like staggered lists,
      • GridLayoutManager - which supports displaying grids as seen in Gallery apps.
    • Item Animator ListViews are lacking in support of good animations, but the RecyclerView brings a whole new dimension to it. Using the RecyclerView.ItemAnimator class, animating the views becomes so much easy and intuitive.

    • Item Decoration In case of ListViews, dynamically decorating items like adding borders or dividers was never easy. But in case of RecyclerView, the RecyclerView.ItemDecorator class gives huge control to the developers but makes things a bit more time consuming and complex.

    From Android Interview Questions (Apache 2.0)

  11. How to communicate with fragments?

    Communicating with fragments

    To reuse fragments, build them as completely self-contained components that define their own layout and behavior. Once you define these reusable fragments, you can associate them with an activity and connect them with the application logic to realize the overall composite UI.

    To properly react to user events and to share state information, you often need to have channels of communication between an activity and its fragments or between two or more fragments. To keep fragments self-contained, don't have fragments communicate directly with other fragments or with their host activity.

    The Fragment library provides two options for communication: a shared ViewModel and the Fragment Result API. The recommended option depends on the use case. To share persistent data with custom APIs, use a ViewModel. For a one-time result with data that can be placed in a Bundle, use the Fragment Result API.1

    Share data using a ViewModel

    ViewModel is an ideal choice when you need to share data between multiple fragments or between fragments and their host activity. ViewModel objects store and manage UI data.

    Share data with the host activity

    In some cases, you might need to share data between fragments and their host activity. For example, you might want to toggle a global UI component based on an interaction within a fragment.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  12. How to support different screen size in android?

    How to support different screen sizes in Android?

    Android devices come in all shapes and sizes, so your app's layout needs to be flexible. That is, instead of defining your layout with rigid dimensions that assume a certain screen size and aspect ratio(width to the height of a screen), your layout should gracefully respond to different screen sizes and orientations.

    By supporting as many screens as possible, your app can be made available to the greatest number of users with different devices, using a single APK. Additionally, making your app flexible for different screen sizes ensures that your app can handle window configuration changes on the device, such as when the user enables multi-window mode.

    You can provide support to different screen sizes by the following techniques:-
    (The following won't necessarily support Android form factors as Android Wear, TV, Auto, and Chrome OS devices)

    Use view dimensions that allow the layout to resize

    Use ConstraintLayout

    The best way to create a responsive layout for different screen sizes is to use ConstraintLayout as the base layout in your UI. ConstraintLayout allows you to specify the position and size for each view according to spatial relationships with other views in the layout. This way, all the views can move and stretch together as the screen size changes.

    The easiest way to build a layout with ConstraintLayout is to use the Layout Editor in Android Studio. It allows you to drag new views to the layout, attach their constraints to the parent view and other sibling views, and edit the view's properties, all without editing any XML by hand.

    (no matter what layout you use, you should always avoid hard-coding layout sizes)

    note:-

    To ensure that your layout is flexible and adapts to different screen sizes, you should use "wrap_content" and "match_parent" for the width and height of most view components, instead of hard-coded sizes. "wrap_content" tells the view to set its size to whatever is necessary to fit the content within that view. "match_parent" makes the view expand to as much as possible within the parent view

    Create alternative layouts

    If the above option doesn't meet your needs,say you need to support a much larger device like tabs,then your app should also provide alternative layout resources to optimize the UI design for certain screen sizes.(As indicated in the image below)

    You can provide screen-specific layouts by creating additional res/layout/ directories—one for each screen configuration that requires a different layout—and then append a screen configuration qualifier to the layout directory name (such as layout-w600dp for screens that have 600dp of available width). These configuration qualifiers represent the visible screen space available for your app UI. The system takes into account any system decorations (such as the navigation bar) and window configuration changes (such as when the user enables multi-window mode) when selecting the layout from your app.

    To create an alternative layout in Android Studio (using version 3.0 or higher), proceed as follows:

    1. Open your default layout and then click Orientation for Preview in the toolbar.
    2. In the drop-down list, click to create a suggested variant such as Create Landscape Variant or click Create Other.
    3. If you selected Create Other, the Select Resource Directory appears. Here, select a screen qualifier on the left and add it to the list of Chosen qualifiers. When you're done adding qualifiers, click OK.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  13. Explain: Main components of Android application

    Main components of android application

    Application components are the essential building blocks of an Android application. These components are loosely coupled by the application manifest file AndroidManifest.xml that describes each component of the application and how they interact.

    Main components of android application are:

    • Activities
    • Services
    • Broadcast Receivers
    • Content Providers

    A Activity represents a single screen with a user interface, in-short Activity performs actions on the screen. An activity provides the window in which the app draws its UI. This window typically fills the screen, but may be smaller than the screen and float on top of other windows. Generally, one activity implements one screen in an app. For instance, one of an app’s activities may implement a Preferences screen, while another activity implements a Select Photo screen. In new architectural approaches, there is only one activity for the entire application, and it controls the fragments that interact with the user.

    A Service is an application component that can perform long-running operations in the background, and it doesn't provide a user interface. Another application component can start a service, and it continues to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service can handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.

    A Broadcast Receivers (receiver) is an Android component which allows you to register for system or application events. Android apps can send or receive broadcast messages from the Android system and other Android apps, similar to the publish-subscribe design pattern. These broadcasts are sent when an event of interest occurs. For example, the Android system sends broadcasts when various system events occur, such as when the system boots up or the device starts charging. Apps can also send custom broadcasts, for example, to notify other apps of something that they might be interested in (for example, some new data has been downloaded).

    A Content Provider manages access to a central repository of data. You implement a provider as one or more classes in an Android application, along with elements in the manifest file. One of your classes implements a subclass ContentProvider, which is the interface between your provider and other applications. Although content providers are meant to make data available to other applications, you may of course have activities in your application that allow the user to query and modify the data managed by your provider.

    Links

    https://www.tutorialspoint.com/android/android_application_components.htm
    https://developer.android.com/guide/components/activities/intro-activities
    https://developer.android.com/guide/components/services
    https://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html
    https://developer.android.com/guide/topics/providers/content-provider-creating

    From Android Interview Questions (Apache 2.0)

  14. Explain: Service vs IntentService

    Service vs IntentService

    A Service is an application component that can perform long-running operations in the background, and it doesn't provide a user interface. Another application component can start a service, and it continues to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC).

    The Service class is the base class for all services. When you extend this class, it's important to create a new thread in which the service can complete all of its work; the service uses your application's main thread by default, which can slow the performance of any activity that your application is running.

    The Android framework also provides the IntentService subclass of Service that uses a worker thread to handle all of the start requests, one at a time. IntentService is very similura to queue where it handles request (intents) from clients. Client can send the request to IntentService by using command - Context.startService(Intent). For implements IntentService you should extend IntentService class and implements method - onHandleIntent(Intent)

    Using IntentService is not recommended for new apps as it will not work well starting with Android 8 Oreo, due to the introduction of Background execution limits. Moreover, it's deprecated starting with Android 11. You can use JobIntentService as a replacement for IntentService that is compatible with newer versions of Android.

    Service IntentService
    Is invoked using startService() Is invoked using Intent
    Can be invoked from any thread Can in invoked from the Main thread only
    Runs background operations on the Main Thread of the Application by default. Hence it can block your Application’s UI Creates a separate worker thread to run background operations
    Invoked multiple times would create multiple instances. Invoked multiple times won’t create multiple instances
    Needs to be stopped using stopSelf() or stopService() Automatically stops after the queue is completed. No need to trigger stopService() or stopSelf()
    Can run parallel operations Multiple intent calls are automatically queued and they would be executed sequentially

    Links

    https://developer.android.com/guide/components/services
    https://www.journaldev.com/20735/android-intentservice-broadcastreceiver
    https://stackoverflow.com/questions/15524280/service-vs-intentservice-in-the-android-platform

    From Android Interview Questions (Apache 2.0)

  15. Explain: View lifecycle

    View lifecycle

    View class represents the basic building block for user interface components. A View occupies a rectangular area on the screen and is responsible for drawing and event handling. View is the base class for widgets, which are used to create interactive UI components (buttons, text fields, etc.).

    Every Activity has it’s own lifecycle similarly Views also have a lifecycle. A view which was rendered on the screen must undergo these lifecycle methods to get drawn on the screen correctly.

    • onAttachedToWindow() - Called when the view is attached to a window. This is the phase where the view knows it can be active and has a surface for drawing. So we can start allocating any resources or set up listeners.
    • onFinishInflate() - Called after a view and all of its children has been inflated from XML.
    • onMeasure(int, int) - Called to determine the size requirements for this view and all of its children.
    • onLayout(boolean, int, int, int, int) - Called when this view should assign a size and position to all of its children.
    • onSizeChanged(int, int, int, int) - Called when the size of this view has changed.
    • onDraw(android.graphics.Canvas) - Canvas object generated (or updates) has a list of OpenGL-ES commands (displayList) to send to the GPU. Never create objects in onDraw() as it gets called a number of times.
    • invalidate() - method that insists on force reDrawing of a particular view that we wish to show changes. Needs to be called when there was a change in view’s appearance.
    • requestLayout() - At some point, there is a state change in the view. requestLayout() is the signal to the view system that it needs to recalculate the Measure and Layout phase of the views (measure → layout → draw).
    • onDetachedFromWindow() - This is called when the view is detached from a window. At this point, it no longer has a surface for drawing. This place where you need to stop doing any kind of work that is scheduled or clean up resources that are allocated. This method is called when we call remove view on the ViewGroup or when the Activity is destroyed etc.

    Links

    https://proandroiddev.com/the-life-cycle-of-a-view-in-android-6a2c4665b95e
    https://codentrick.com/android-view-lifecycle/
    https://medium.com/@sahoosunilkumar/understanding-view-lifecycle-in-android-e42890aab16
    https://developer.android.com/reference/android/view/View

    From Android Interview Questions (Apache 2.0)

  16. What are Sticky Intent?

    Sticky Intent

    Sticky Intent - Sticks with Android, for future broadcast listeners. For example if BATTERY_LOW event occurs then that intent will stick with Android so that any future requests for BATTERY_LOW, will return the intent. Sticky Intent is also a type of Intent which allows communication between a function and a service sendStickyBroadcast(), performs a sendBroadcast(Intent), the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter). In all other ways, this behaves the same as sendBroadcast(Intent).

    Links

    https://stackoverflow.com/questions/26038839/knowing-about-sticky-intent-in-android

    From Android Interview Questions (Apache 2.0)

  17. What are the permission protection levels?

    Protection levels in permission

    Normal - The default value. A lower-risk permission that gives requesting applications access to isolated application-level features, with minimal risk to other applications, the system, or the user. The system automatically grants this type of permission to a requesting application at installation, without asking for the user's explicit approval (though the user always has the option to review these permissions before installing).

    Dangerous - A higher-risk permission that would give a requesting application access to private user data or control over the device that can negatively impact the user. Because this type of permission introduces potential risk, the system may not automatically grant it to the requesting application. For example, any dangerous permissions requested by an application may be displayed to the user and require confirmation before proceeding, or some other approach may be taken to avoid the user automatically allowing the use of such facilities.

    Signature - A permission that the system grants only if the requesting application is signed with the same certificate as the application that declared the permission. If the certificates match, the system automatically grants the permission without notifying the user or asking for the user's explicit approval.

    SignatureOrSystem - Old synonym for "signature|privileged". Deprecated in API level 23.

    A permission that the system grants only to applications that are in a dedicated folder on the Android system image or that are signed with the same certificate as the application that declared the permission. Avoid using this option, as the signature protection level should be sufficient for most needs and works regardless of exactly where apps are installed. The "signatureOrSystem" permission is used for certain special situations where multiple vendors have applications built into a system image and need to share specific features explicitly because they are being built together.

    Links

    https://developer.android.com/guide/topics/manifest/permission-element

    From Android Interview Questions (Apache 2.0)

  18. What do you know about Activity Result APIs?

    Activity Result APIs

    While the underlying startActivityForResult() and onActivityResult() APIs are available on the Activity class on all API levels, it is strongly recommended to use the Activity Result APIs introduced in AndroidX Activity and Fragment.

    Registering a callback for an Activity Result

    When starting an activity for a result, it is possible (and, in cases of memory-intensive operations such as camera usage, almost certain) that your process and your activity will be destroyed due to low memory.

    For this reason, the Activity Result APIs decouple the result callback from the place in your code where you launch the other activity. As the result callback needs to be available when your process and activity are recreated, the callback must be unconditionally registered every time your activity is created, even if the logic of launching the other activity only happens based on user input or other business logic.

    When in a ComponentActivity or a Fragment, the Activity Result APIs provide a registerForActivityResult() API for registering the result callback. registerForActivityResult() takes an ActivityResultContract and an ActivityResultCallback and returns an ActivityResultLauncher which you’ll use to launch the other activity.

    An ActivityResultContract defines the input type needed to produce a result along with the output type of the result. The APIs provide default contracts for basic intent actions like taking a picture, requesting permissions, and so on. You can also create your own custom contracts.

    ActivityResultCallback is a single method interface with an onActivityResult() method that takes an object of the output type defined in the ActivityResultContract:

    val getContent = registerForActivityResult(GetContent()) { uri: Uri? ->
        // Handle the returned Uri
    }
    

    If you have multiple activity result calls that either use different contracts or want separate callbacks, you can call registerForActivityResult() multiple times to register multiple ActivityResultLauncher instances. You must always call registerForActivityResult() in the same order for each creation of your fragment or activity to ensure that the inflight results are delivered to the correct callback.

    registerForActivityResult() is safe to call before your fragment or activity is created, allowing it to be used directly when declaring member variables for the returned ActivityResultLauncher instances.

    Launching an activity for result

    While registerForActivityResult() registers your callback, it does not launch the other activity and kick off the request for a result. Instead, this is the responsibility of the returned ActivityResultLauncher instance.

    If input exists, the launcher takes the input that matches the type of the ActivityResultContract. Calling launch() starts the process of producing the result. When the user is done with the subsequent activity and returns, the onActivityResult() from the ActivityResultCallback is then executed, as shown in the following example:

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  19. What do you know about App Bundles?

    App Bundles

    An Android App Bundle is a publishing format that includes all your app’s compiled code and resources, and defers APK generation and signing to Google Play.

    Google Play uses your app bundle to generate and serve optimized APKs for each device configuration, so only the code and resources that are needed for a specific device are downloaded to run your app. You no longer have to build, sign, and manage multiple APKs to optimize support for different devices, and users get smaller, more-optimized downloads.

    When you use the app bundle format to publish your app, you can also optionally take advantage of Play Feature Delivery, which allows you to add feature modules to your app project. hese modules contain features and resources that are only included with your app based on conditions that you specify, or are available later at runtime for download Using the Play Core Library.

    What's the difference between AABs and APKs?

    App bundles are only for publishing and cannot be installed on Android devices. The Android package (APK) is Android's installable, executable format for apps. App bundles must be processed by a distributor into APKs so that they can be installed on devices.

    APK AAB
    Upload to Google Play and install directly on devices Upload to Google Play only
    No reduction in download size via dynamic delivery Supports dynamic delivery
    Supports developer or Google signing Google signing only

    Compressed download size restriction

    Publishing with Android App Bundles helps your users to install your app with the smallest downloads possible and increases the compressed download size limit to 150 MB. hat is, when a user downloads your app, the total size of the compressed APKs required to install your app (for example, the base APK + configuration APKs) must be no more than 150 MB. Any subsequent downloads, such as downloading a feature module (and its configuration APKs) on demand, must also meet this compressed download size restriction. Asset packs do not contribute to this size limit, but they do have other size restrictions.

    Links

    About Android App Bundles

    Android App Bundle frequently asked questions

    Android App Bundle (AAB)

    From Android Interview Questions (Apache 2.0)

  20. What do you know about App Shortcuts?

    App Shortcuts

    Shortcuts deliver specific types of content to your users by helping them quickly access parts of your app.1

    As a developer, you can define shortcuts to perform specific actions in your app. You can display these shortcuts in a supported launcher or assistant—like Google Assistant—and help your users quickly start common or recommended tasks within your app.2

    Each shortcut references one or more intents, each of which launches a specific action in your app when users select the shortcut. The types of shortcuts you create for your app depend on the app's use case.3

    You can publish the following types of shortcuts for your app:4

    • Static shortcuts are defined in a resource file that is packaged into an APK or app bundle;
    • Dynamic shortcuts can be pushed, updated, and removed by your app only at runtime;
    • Pinned shortcuts can be added to supported launchers at runtime if the user grants permission.

    Static shortcuts

    Static shortcuts are best for apps that link to content using a consistent structure throughout the lifetime of a user's interaction with the app. Because most launchers only display four shortcuts at once, static shortcuts are useful for performing a routine task in a consistent way, such as if the user wants to view their calendar or email in a specific way.

    To create a static shortcut, do the following:

    • In your app's AndroidManifest.xml file, find the activity whose intent filters are set to the android.intent.action.MAIN action and the android.intent.category.LAUNCHER category;
    • Add a <meta-data> element to this activity that references the resource file where the app's shortcuts are defined;
    • Create a new resource file called res/xml/shortcuts.xml;
    • In the new resource file, add a <shortcuts> root element that contains a list of <shortcut> elements. In each <shortcut> element, include information about a static shortcut including its icon, description labels, and the intents it launches within the app.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  21. What do you know about App Startup library?

    App Startup

    The App Startup library provides a straightforward, performant way to initialize components at application startup. Both library developers and app developers can use App Startup to streamline startup sequences and explicitly set the order of initialization.

    Instead of defining separate content providers for each component you need to initialize, App Startup allows you to define component initializers that share a single content provider. This can significantly improve app startup time.

    Initialize components at app startup

    Apps and libraries often rely on having components initialized right away when the app starts up. You can meet this need by using content providers to initialize each dependency, but content providers are expensive to instantiate and can slow down the startup sequence unnecessarily. Additionally, Android initializes content providers in an undetermined order. App Startup provides a more performant way to initialize components at app startup and explicitly define their dependencies.

    To use App Startup to initialize components automatically at startup, you must define a component initializer for each component that the app needs to initialize.

    Implement component initializers

    You define each component initializer by creating a class that implements the Initializer<T> interface. This interface defines two important methods:

    • The create() method, which contains all of the necessary operations to initialize the component and returns an instance of T.
    • The dependencies() method, which returns a list of the other Initializer<T> objects that the initializer depends on. You can use this method to control the order in which the app runs the initializers at startup.

    For example, suppose that your app depends on WorkManager and needs to initialize it at startup. Define a WorkManagerInitializer class that implements Initializer<WorkManager>:

    // Initializes WorkManager.
    class WorkManagerInitializer : Initializer<WorkManager> {
        override fun create(context: Context): WorkManager {
            val configuration = Configuration.Builder().build()
            WorkManager.initialize(context, configuration)
            return WorkManager.getInstance(context)
        }
        override fun dependencies(): List<Class<out Initializer<*>>> {
            // No dependencies on other libraries.
            return emptyList()
        }
    }
    

    The dependencies() method returns an empty list because WorkManager does not depend on any other libraries.

    Suppose that your app also depends on a library called ExampleLogger, which in turn depends on WorkManager. This dependency means that you need to make sure that App Startup initializes WorkManager first. Define an ExampleLoggerInitializer class that implements Initializer<ExampleLogger>:

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  22. What do you know about ArrayMap?

    ArrayMap

    ArrayMap is a generic key->value mapping data structure that is designed to be more memory efficient than a traditional HashMap. It keeps its mappings in an array data structure - an integer array of hash codes for each item, and an Object array of the key/value pairs. This allows it to avoid having to create an extra object for every entry put in to the map, and it also tries to control the growth of the size of these arrays more aggressively (since growing them only requires copying the entries in the array, not rebuilding a hash map).

    Note that this implementation is not intended to be appropriate for data structures that may contain large numbers of items. It is generally slower than a traditional HashMap, since lookups require a binary search and adds and removes require inserting and deleting entries in the array. For containers holding up to hundreds of items, the performance difference is not significant, less than 50%.

    Because this container is intended to better balance memory use, unlike most other standard Java containers it will shrink its array as items are removed from it. Currently you have no control over this shrinking - if you set a capacity and then remove an item, it may reduce the capacity to better match the current size. In the future an explicit call to set the capacity should turn off this aggressive shrinking behavior.

    This structure is NOT thread-safe.

    How ArrayMap works

    ArrayMap uses 2 arrays. The instance variables used internally are Object[] mArray to store the objects and the int[] mHashes to store hashCodes. When a key/value is inserted:

    • Key/Value is autoboxed;
    • The key object is inserted in the mArray where on the index in which it needs to pushed is searched using the binary search;
    • A value object is also inserted in the position next to key’s position in mArray[];
    • The hashCode of the key is calculated and placed in mHashes[] at the next available position.

    For searching a key:

    • Key’s hashCode is calculated;
    • Binary search is done for this hashCode in the mHashes array. This implies time complexity increases to O(logN);
    • Once we get the index of hash, we know that key is at 2*index position in mArray and value is at 2*index+1 position;
    • Here the time complexity increases from O(1) to O(logN), but it is memory efficient. Whenever we play on a dataset of around 100, there will no problem of time complexity, it will be non-noticeable. As we have the advantage of memory efficient application.

    Example of usage

    import androidx.collection.ArrayMap
    class ArrayMapExample {
        fun example() {
            val arrayMap = ArrayMap<String, String>()
            arrayMap["USA"] = "Washington"
            arrayMap["Germany"] = "Berlin"
            arrayMap["France"] = "Paris"
            arrayMap["Italy"] = "Rome"
            arrayMap["Australia"] = "Canberra"
            for (i in 0 until arrayMap.size) {
                println("Country = " + arrayMap.keyAt(i) + ", Capital = " + arrayMap.valueAt(i))
            }
        }
    }
    

    Output:

    Country = Australia, Capital = Canberra
    Country = USA, Capital = Washington
    Country = Italy, Capital = Rome
    Country = Germany, Capital = Berlin
    Country = France, Capital = Paris
    

    Links

    https://developer.android.com/reference/android/util/ArrayMap
    https://medium.com/@mohom.r/optimising-android-app-performance-with-arraymap-9296f4a1f9eb

    From Android Interview Questions (Apache 2.0)

  23. What do you know about Auto Backup?

    What do you know about Auto Backup?

    Auto Backup for Apps automatically backs up a user's data from apps that target and run on Android 6.0 (API level 23) or higher. Android preserves app data by uploading it to the user's Google Drive, where it's protected by the user's Google account credentials. The backup is end-to-end encrypted on devices running Android 9 or higher using the device's PIN, pattern, or password.

    Backup data is stored in a private folder in the user's Google Drive account, limited to 25 MB per app. There's no charge for storing backup data. The saved data does not count toward the user's personal Google Drive quota. Only the most recent backup is stored. When a backup is made, any previous backup is deleted. The backup data can't be read by the user or other apps on the device. Your app can customize the backup process or opt out by disabling backups.

    From Android 12 (API level 31) Android backup and restore has two forms:

    • Cloud backups: User data is stored in a user’s Google Drive so that it can later be restored on that device or a new device;
    • Device-to-device (D2D) transfers: User data is sent directly to the user's new device from their older device, such as by using a cable.

    Files that are backed up

    By default, Auto Backup includes files in most of the directories that are assigned to your app by the system:

    • Shared preferences files;
    • Files saved to your app's internal storage and accessed by getFilesDir() or getDir(String, int);
    • Files in the directory returned by getDatabasePath(String), which also includes files created with the SQLiteOpenHelper class;
    • Files on external storage in the directory returned by getExternalFilesDir(String).

    Auto Backup excludes files in directories returned by getCacheDir(), getCodeCacheDir(), and getNoBackupFilesDir(). The files saved in these locations are needed only temporarily and are intentionally excluded from backup operations.

    Enable and disable backup

    Apps that target Android 6.0 (API level 23) or higher automatically participate in Auto Backup. In your app manifest file, set the boolean value android:allowBackup to enable or disable backup. The default value is true, but we recommend explicitly setting the attribute in your manifest, as shown below:

    <manifest ... >
        ...
        <application android:allowBackup="true" ... >
            ...
        </application>
    </manifest>
    

    You can disable backups by setting android:allowBackup to false. You might want to do this if your app can recreate its state through some other mechanism or if your app deals with sensitive information.

    Note. For apps running on and targeting Android 12 (API level 31) or higher, specifying android:allowBackup="false" disables backups to Google Drive but doesn’t disable device-to-device transfers for the app.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  24. What do you know about Chrome custom tabs?

    Chrome custom tabs

    App developers face a choice when a user taps a URL to either launch a browser, or build their own in-app browser using WebViews.

    Both options present challenges - launching the browser is a heavy context switch for users that isn't customizable, while WebViews don't support all features of the web platform, don't share state with the browser and add maintenance overhead.

    Custom Tabs is a browser feature, introduced by Chrome, that is now supported by most major browsers on Android. It give apps more control over their web experience, and make transitions between native and web content more seamless without having to resort to a WebView.

    Custom Tabs allow an app to customize how the browser looks and feels. An app can change things like:

    • Toolbar color;
    • Enter and exit animations;
    • Add custom actions to the browser toolbar, overflow menu and bottom toolbar.

    Custom Tabs also allow the developer to pre-start the browser and pre-fetch content for faster loading. Custom Tabs is a feature supported by browsers on the Android platform. It was originally introduced by Chrome, on version 45. Currentely, the protocol is supported by most Android browsers.

    When should I use Custom Tabs vs WebView?

    The WebView is good solution if you are hosting your own content inside your app. If your app directs people to URLs outside your domain, we recommend that you use Custom Tabs for these reasons:

    • Support for the same web platform features and capabilities as the browsers;
    • Simple to implement. No need to build code to manage requests, permission grants or cookie stores;
    • UI customization:
      • Toolbar color
      • Action button
      • Custom menu items
      • Custom in/out animations
      • Bottom toolbar
    • Navigation awareness: the browser delivers a callback to the application upon an external navigation;
    • Security: the browser uses Google's Safe Browsing to protect the user and the device from dangerous sites;
    • Performance optimization:
      • Pre-warming of the Browser in the background, while avoiding stealing resources from the application.
      • Providing a likely URL in advance to the browser, which may perform speculative work, speeding up page load time.
    • Lifecycle management: the browser prevents the application from being evicted by the system while on top of it, by raising its importance to the "foreground" level;
    • Shared cookie jar and permissions model so users don't have to sign-in to sites they are already connected to, or re-grant permissions they have already granted;
    • If the user has turned on Data Saver, they will still benefit from it;
    • Synchronized AutoComplete across devices for better form completion;
    • Simple customization model;
    • Quickly return to app with a single tap;
    • You want to use the latest browser implementations on devices pre-Lollipop (auto updating WebView) instead of older WebViews.

    Links

    https://developers.google.com/web/android/custom-tabs
    https://developers.google.com/web/android/custom-tabs/implementation-guide

    From Android Interview Questions (Apache 2.0)

  25. What do you know about CompositionLocal?

    CompositionLocal

    Usually in Compose, data flows down through the UI tree as parameters to each composable function. This makes a composable’s dependencies explicit. This can however be cumbersome for data that is very frequently and widely used such as colors or type styles. See the following example:

    @Composable
    fun MyApp() {
        // Theme information tends to be defined near the root of the application
        val colors = colors()
    }
    // Some composable deep in the hierarchy
    @Composable
    fun SomeTextLabel(labelText: String) {
        Text(
            text = labelText,
            color = colors.onPrimary // ← need to access colors here
        )
    }
    

    To support not needing to pass the colors as an explicit parameter dependency to most composables, Compose offers CompositionLocal which allows you to create tree-scoped named objects that can be used as an implicit way to have data flow through the UI tree.

    CompositionLocal elements are usually provided with a value in a certain node of the UI tree. That value can be used by its composable descendants without declaring the CompositionLocal as a parameter in the composable function.1

    Example of usage of CompositionLocal:

    data class UserPreferences(val isDarkModeEnabled: Boolean, val fontSize: Float)
    // Define a dynamic Composition Local with default preferences
    val LocalUserPreferences = compositionLocalOf {
        UserPreferences(isDarkModeEnabled = false, fontSize = 14f)
    }
    @Composable
    fun PreferencesProvider(content: @Composable () -> Unit) {
        var isDarkMode by remember { mutableStateOf(false) }
        val preferences = UserPreferences(isDarkMode, 16f)
        CompositionLocalProvider(LocalUserPreferences provides preferences) {
            content()
        }
    }
    @Composable
    fun SettingsScreen() {
        val preferences = LocalUserPreferences.current
        Text("Dark Mode: ${if (preferences.isDarkModeEnabled) "Enabled" else "Disabled"}")
    }
    

    Explanation:

    • Definition. The UserPreferences data class holds dynamic user settings;
    • Provision. The PreferencesProvider dynamically updates and provides the preferences based on the user's actions;
    • Consumption. The SettingsScreen consumes and displays the preferences, updating reactively when changes occur.2

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  26. What do you know about Converters in Room?

    Converters in Room

    Sometimes, you need your app to store a custom data type in a single database column. You support custom types by providing type converters, which are methods that tell Room how to convert custom types to and from known types that Room can persist. You identify type converters by using the @TypeConverter annotation.

    Suppose you need to persist instances of Date in your Room database. Room doesn't know how to persist Date objects, so you need to define type converters:

    class Converters {
      @TypeConverter
      fun fromTimestamp(value: Long?): Date? {
        return value?.let { Date(it) }
      }
      @TypeConverter
      fun dateToTimestamp(date: Date?): Long? {
        return date?.time?.toLong()
      }
    }
    

    This example defines two type converter methods: one that converts a Date object to a Long object, and one that performs the inverse conversion from Long to Date. Because Room knows how to persist Long objects, it can use these converters to persist Date objects.

    Next, you add the @TypeConverters annotation to the AppDatabase class so that Room knows about the converter class that you have defined:

    @Database(entities = arrayOf(User::class), version = 1)
    @TypeConverters(Converters::class)
    abstract class AppDatabase : RoomDatabase() {
      abstract fun userDao(): UserDao
    }
    

    With these type converters defined, you can use your custom type in your entities and DAOs just as you would use primitive types:

    @Entity
    data class User(private val birthday: Date?)
    @Dao
    interface UserDao {
      @Query("SELECT * FROM user WHERE birthday = :targetDate")
      fun findUsersBornOnDate(targetDate: Date): List<User>
    }
    

    In this example, Room can use the defined type converter everywhere because you annotated AppDatabase with @TypeConverters. However, you can also scope type converters to specific entities or DAOs by annotating your @Entity or @Dao classes with @TypeConverters.

    Control type converter initialization

    Ordinarily, Room handles instantiation of type converters for you. However, sometimes you might need to pass additional dependencies to your type converter classes, which means that you need your app to directly control initialization of your type converters. In that case, annotate your converter class with @ProvidedTypeConverter:

    @ProvidedTypeConverter
    class ExampleConverter {
      @TypeConverter
      fun StringToExample(string: String?): ExampleType? {
        ...
      }
      @TypeConverter
      fun ExampleToString(example: ExampleType?): String? {
        ...
      }
    }
    

    Then, in addition to declaring your converter class in @TypeConverters, use the RoomDatabase.Builder.addTypeConverter() method to pass an instance of your converter class to the RoomDatabase builder:

    val db = Room.databaseBuilder(...)
      .addTypeConverter(exampleConverterInstance)
      .build()
    

    Understand why Room doesn't allow object references

    Mapping relationships from a database to the respective object model is a common practice and works very well on the server side. Even when the program loads fields as they're accessed, the server still performs well.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  27. What do you know about DiffUtil?

    DiffUtil

    DiffUtil is a utility class that calculates the difference between two lists and outputs a list of update operations that converts the first list into the second one.

    It can be used to calculate updates for a RecyclerView Adapter. See ListAdapter and AsyncListDiffer which can simplify the use of DiffUtil on a background thread.

    DiffUtil uses Eugene W. Myers's difference algorithm to calculate the minimal number of updates to convert one list into another. Myers's algorithm does not handle items that are moved so DiffUtil runs a second pass on the result to detect items that were moved.

    Note that DiffUtil, ListAdapter, and AsyncListDiffer require the list to not mutate while in use. This generally means that both the lists themselves and their elements (or at least, the properties of elements used in diffing) should not be modified directly. Instead, new lists should be provided any time content changes. It's common for lists passed to DiffUtil to share elements that have not mutated, so it is not strictly required to reload all data to use DiffUtil.

    If the lists are large, this operation may take significant time so you are advised to run this on a background thread, get the DiffUtil.DiffResult then apply it on the RecyclerView on the main thread.

    DiffUtil.Callback

    DiffUtil.Callback class used by DiffUtil while calculating the diff between two lists.

    Method Description
    abstract Boolean areContentsTheSame(oldItemPosition: Int, newItemPosition: Int) Called by the DiffUtil when it wants to check whether two items have the same data.
    abstract Boolean areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) Called by the DiffUtil to decide whether two object represent the same Item.
    open Any? getChangePayload(oldItemPosition: Int, newItemPosition: Int) When areItemsTheSame(int, int) returns true for two items and areContentsTheSame(int, int) returns false for them, DiffUtil calls this method to get a payload about the change.
    abstract Int getNewListSize() Returns the size of the new list.
    abstract Int getOldListSize() Returns the size of the old list.

    Links

    https://developer.android.com/reference/androidx/recyclerview/widget/DiffUtil
    https://developer.android.com/reference/kotlin/androidx/recyclerview/widget/DiffUtil.Callback
    https://medium.com/@iammert/using-diffutil-in-android-recyclerview-bdca8e4fbb00

    From Android Interview Questions (Apache 2.0)

  28. What do you know about FileProvider?

    FileProvider

    FileProvider is a special subclass of ContentProvider that facilitates secure sharing of files associated with an app by creating a content:// Uri for a file instead of a file:/// Uri.

    A content URI allows you to grant read and write access using temporary access permissions. When you create an Intent containing a content URI, in order to send the content URI to a client app, you can also call Intent.setFlags() to add permissions. These permissions are available to the client app for as long as the stack for a receiving Activity is active. For an Intent going to a Service, the permissions are available as long as the Service is running.

    In comparison, to control access to a file:/// Uri you have to modify the file system permissions of the underlying file. The permissions you provide become available to any app, and remain in effect until you change them. This level of access is fundamentally insecure.

    The increased level of file access security offered by a content URI makes FileProvider a key part of Android's security infrastructure.

    Defining a FileProvider

    Since the default functionality of FileProvider includes content URI generation for files, you don't need to define a subclass in code. Instead, you can include a FileProvider in your app by specifying it entirely in XML. To specify the FileProvider component itself, add a <provider> element to your app manifest. Set the android:name attribute to androidx.core.content.FileProvider. Set the android:authorities attribute to a URI authority based on a domain you control; for example, if you control the domain mydomain.com you should use the authority com.mydomain.fileprovider. Set the android:exported attribute to false; the FileProvider does not need to be public. Set the android:grantUriPermissions attribute to true, to allow you to grant temporary access to files. For example:

    <manifest>
        ...
        <application>
            ...
            <provider
                android:name="androidx.core.content.FileProvider"
                android:authorities="com.mydomain.fileprovider"
                android:exported="false"
                android:grantUriPermissions="true">
                ...
            </provider>
            ...
        </application>
    </manifest>
    

    Specifying Available Files

    A FileProvider can only generate a content URI for files in directories that you specify beforehand. To specify a directory, specify its storage area and path in XML, using child elements of the <paths> element. For example, the following paths element tells FileProvider that you intend to request content URIs for the images/ subdirectory of your private file area.

    <paths xmlns:android="http://schemas.android.com/apk/res/android">
        <files-path name="my_images" path="images/"/>
        ...
    </paths>
    

    The <paths> element must contain one or more of the following child elements:

    <files-path name="name" path="path" />
    

    These child elements all use the same attributes:

    name="name". A URI path segment. To enforce security, this value hides the name of the subdirectory you're sharing. The subdirectory name for this value is contained in the path attribute.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  29. What do you know about Foreground Services?

    Foreground Services

    Foreground services perform operations that are noticeable to the user.

    Foreground services show a status bar notification, to make users aware that your app is performing a task in the foreground and is consuming system resources.

    Examples of apps that use foreground services include the following:

    • A music player app that plays music in a foreground service. The notification might show the current song being played;
    • A fitness app that records a user's run in a foreground service, after receiving permission from the user. The notification might show the distance that the user has traveled during the current fitness session;

    Only use a foreground service when your app needs to perform a task that is noticeable by the user, even when they're not directly interacting with the app.1

    Starting in Android 13 (API level 33), users can dismiss the notification associated with a foreground service by default. To do so, users perform a swipe gesture on the notification. Traditionally, the notification isn't dismissed unless the foreground service is either stopped or removed from the foreground.2

    Declare foreground services in your manifest

    In your app's manifest, declare each of your app's foreground services with a <service> element. For each service, use an android:foregroundServiceType attribute to declare what kind of work the service does.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

  30. What do you know about Handler, MessageQueue, Looper?

    Handler, MessageQueue, Looper

    Main classes

    To describe the whole flow, we need to understand what the purpose of the following classes:

    • Runnable;
    • Thread;
    • Message;
    • MessageQueue;
    • Handler;
    • Looper.

    Runnable

    The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run.

    This interface is designed to provide a common protocol for objects that wish to execute code while they are active. Being active simply means that a thread has been started and has not yet been stopped.

    Thread

    A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.

    Java offers two types of threads: user threads and daemon threads.

    User threads are high-priority threads. The JVM will wait for any user thread to complete its task before terminating it.

    On the other hand, daemon threads are low-priority threads whose only role is to provide services to user threads.

    Since daemon threads are meant to serve user threads and are only needed while user threads are running, they won't prevent the JVM from exiting once all user threads have finished their execution. source

    When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class).

    When an application is launched in Android, it creates the first thread of execution, known as the "main" thread. The main thread is responsible for dispatching events to the appropriate user interface widgets as well as communicating with components from the Android UI toolkit.

    Message, MessageQueue

    Message defines a message containing a description and arbitrary data object. This object contains two extra int fields and an extra object field that allow you to not do allocations in many cases.

    MessageQueue is low-level class holding the list of messages. When a process is created for your application, its main thread is dedicated to running a MessageQueue that takes care of managing the top-level application objects (activities, broadcast receivers, etc) and any windows they create. Messages are not added directly to a MessageQueue, but rather through Handler.

    Handler

    A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. There are two main uses for a Handler:

    • Schedule messages and runnables to be executed at some point in the future;
    • Enqueue an action to be performed on a different thread than your own.

    When you create a new Handler it is bound to a Looper.

    Looper

    The Looper class maintains a MessageQueue and used to run a message loop for a thread. An important character of Looper is that it's associated with the thread within which the Looper is created. This association is kept forever and can't be broken nor changed. Also note that a thread can't be associated with more than one Looper.

    Read the rest at the sourceFrom Android Interview Questions (Apache 2.0)

Related topics

Where these questions come from

Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.