Ultimate database of Android Interview Questions

Ultimate database of Android Interview Questions

1. What is Application in Android?

The Application class in Android is the base class within an Android application that contains all other components such as activities and services. The Application class, or any subclass of the Application class, is instantiated before any other class when the process for the application/package is created.
The manifest file provides essential information about an app to the Android system which the system must have before it can run any of the application’s code.

2. What is Context in Android?

A Context is a handle to the system. It provides services like resolving resources, obtaining access to databases, preferences etc. A Context is like a handle to the environment the application is currently running in.

3. What is the Application Context?

Application Context is the Context that ties to the lifecycle of an application. The Application Context is used where we need a Context whose lifecycle is separate from the current Context or when we need to pass a Context beyond the scope of an Activity.

4. What is an Activity?

An Activity is a container or a window to the user interface. An Android app may contain one or more activities to handle different user interfaces.
In other words, it is an application component that provides a screen with which users can interact to do something, such as dial the phone, take a photo, send an email, or view a map.

5. What is Activity Context?

This Context is available in an Activity and is tied to the lifecycle of an Activity. The Activity Context should be used when we pass the Context in the scope of an Activity, or we need the Context whose lifecycle is attached to the current Context.

6. List the Lifecycle of an Activity

  • onCreate(): called when the view is first created. This is the best point at which we create views, get data from bundles etc.
  • onStart(): called when the Activity is becoming visible to the user.
  • onResume(): called when the Activity will start interacting with the user. At this point, the Activity is at the top of the Activity stack, with user input going into it.
  • onPause(): called as part of the Activity lifecycle when an Activity is going into the background but not yet killed.
  • onStop(): called when the Activity is no longer visible to the user.
  • onDestroy(): called when the Activity is finishing
  • onRestart(): called after an Activity is stopped before it has started again
A simplified illustration of the activity lifecycle.

7. What is the difference between onCreate() and onStart() method?

The onCreate() method is called once during the Activity lifecycle, either when the application starts, or when the Activity has been destroyed and then recreated (for example during a configuration change).
The onStart() method is called whenever the Activity becomes visible to the user, typically after onCreate() or onRestart().

8. When will onDestroy be called for an Activity without onPause() and onStop() being called?

If the function finish() is invoked in the onCreate method of an Activity, the system will invoke the onDestroy() method directly.

9. Why do we call the setContentView() in onCreate() of Activity class?

The onCreate() of an Activity is called only once during an Activity lifecycle. This is the point where most initialisation should take place.
The setContentView() is a heavy operation, and thus, it is inefficient to set the content in onResume() or onStart() since they might be called multiple times.

10. What is onSavedInstanceState() and onRestoreInstanceState() in an Activity?

onSaveInstanceState() – This is a method used to store data before pausing an Activity.
onRestoreInstanceState() – When an Activity is recreated after it was previously destroyed, we can recover the saved state from the Bundle that the system passes to the Activity. Both onCreate() and onRestoreInstanceState() callback methods receive the same Bundle that contains the instance state information.
But, since onCreate() method is called when the system is creating a new instance of our Activity or recreating a previous one, we must check whether the state Bundle is null before we attempt to read it. If it is null, then the system is creating a new instance of the Activity instead of restoring a previous one that was destroyed.

11. How does the Activity respond when the device screen is rotated?

When the device screen is rotated, the current instance of an Activity is destroyed, and a new instance of the same Activity is created in the new orientation.
The onRestart() method is invoked first when the screen is rotated. The other lifecycle methods get invoked in the same sequence as they are when the Activity is first created.

12. What is a Fragment?

A Fragment is a UI entity attached to Activity which provides its own layout. Fragments are reusable components and can be attached to different activities. An Activity can have multiple Fragments attached to it. A Fragment must be attached to an Activity, and its lifecycle will depend on its host Activity.

13. Describe the Fragment Lifecycle

  • onAttach(): A Fragment instance is associated with an Activity instance. The Fragment is not fully initialised at this point. In this method, we get a reference to the Activity which uses the Fragment for further initialisation.
  • onCreate(): The system calls this method when creating the Fragment. We should initialise the essential components of the Fragment that we want to retain when the Fragment resumed after being paused or stopped.
  • onCreateView(): The system calls this method when it is time for the Fragment to draw its user interface for the first time. To draw a UI for a Fragment, we must return a View component from this method which is the root of our Fragment’s layout. If the Fragment does not provide a UI, we can return null from this method.
  • onActivityCreated(): It is called after the onCreateView() method when the host Activity is created. The Activity and Fragment instance, as well as the view hierarchy of the Activity, has been created. At this point, the views can be accessed with the findViewById() method. We can instantiate objects which require a Context object at this point.
  • onStart(): called once the Fragment is visible to the user.
  • onResume(): called when the Fragment becomes active.
  • onPause(): called by the system when the user is leaving the Fragment. This is the point where we should commit any changes that should be persisted beyond the current user session.
  • onStop(): This is called after onPause() when the Fragment is stopped
  • onDestroyView(): The Fragment view will destroy after this method is called
  • onDestroy(): This is not guaranteed to be called by the Android platform. It is used to clean up any final states of the Fragment
The lifecycle of a fragment (while its activity is running).

14. What is a ViewModel?

The ViewModel is a class designed to store and manage UI-related data in a lifecycle conscious way. It is a part of the Android Jetpack library. 
A ViewModel will not be destroyed if its owner is killed for a configuration change like screen rotation. The new instance of the owner will be re-connected to the existing ViewModel. So if we rotate an Activity three times, we have just created three different Activity instances, but we only have one ViewModel.
A common practice is to store data in the ViewModel class (since it persists data during configuration changes) and use onSaveInstanceState() to save small amounts of UI data.

15. How can we prevent the data from being reloaded and reset when the screen is rotated?

The most basic approach would be to use a combination of ViewModels and onSaveInstanceState(). This approach is only suitable for small amounts of data that can be serialised then deserialised. It is not ideal for potentially large amounts of data like a list of items or bitmaps.

16. What is Android Application Architecture?

Android application architecture has the following components:

  • Services − It performs background functionalities
  • Intent − It performs the interconnection between activities and the data passing mechanism
  • Resource Externalisation − Handles Strings and Graphics
  • Notification − Light, Sound, Icon, Notification, Dialog box and Toast
  • Content Providers − It shares data between applications

17. What are Content Providers?

A Content Provider provides data from one application to another on request.
It can use different ways to store its data, and the data can be stored in a database, in files, or even over a network. It manages access to a structured set of data and provides mechanisms for defining data security.
It often provides in its own UI for working with the data.
ContentProvider is the standard interface that connects data in one process with code running in another process.
To access data in a ContentProvider, we must use the ContentResolver object in our application’s Context to communicate with the provider as a client. The provider object receives data requests from clients, performs the requested action, and returns the results.

18. How to access data using Content Provider?

Primarily, the Android application must have the necessary read access permissions.
We need to get access to the ContentResolver object by calling getContentResolver() on the Context object and retrieve the data by constructing a query using ContentResolver.query().
The ContentResolver.query() method returns a Cursor, which we can use to retrieve data from each column using Cursor methods.

19. What are Services in Android?

A Service is an application component that can perform long-running operations in the background. It does not provide a user interface.
It can run in the background even when the user is not interacting with our application.
A service can handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.
These are the three different types of services:

  • Foreground Service: A foreground service performs some operation that is noticeable to the user. For example, an audio app would use a foreground service to play an audio track. Foreground services must display a Notification. Foreground services continue running even when the user isn’t interacting with the app.
  • Background Service: A background service performs an operation that isn’t directly noticed by the user. For example, if an app used a service to compact its storage, that would usually be a background service. In Android API level 26 and above, there are restrictions to using background services, and it is recommended to use WorkManager in such cases.
  • Bound Service: A service is bound when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, receive results, and even do so across processes with interprocess communication (IPC). A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.

20. What is the difference between Service & Intent Service?

Service is the base class for Android services that can be extended to create any service. A class that directly extends Service runs on the Main thread and thus, will block the UI (if there is one) and should therefore either be used only for short tasks or should make use of other threads for long running tasks.
IntentService is a subclass of Service that handles asynchronous requests (expressed as “Intents”) on demand. Clients send requests through startService(Intent) calls. The service is started as needed, handles each Intent, in turn, using a worker thread, and stops itself when it runs out of work.

21. What is the difference between AsyncTasks & Threads?

A thread is used to separate long running operations from Main thread to improve performance. But it cannot be cancelled elegantly, and it cannot handle configuration changes of Android. A thread cannot update the UI, and it may or may not be attached to an Activity or Fragment.
AsyncTask can be used to handle any process that is shorter than 5ms in duration. With AsyncTask, we can update UI, unlike java Thread. But many long running tasks will choke the performance. An AsyncTask is always bound to a particular Activity or Fragment.

22. Why can a byte-code not be run in Android?

Android uses DVM (Dalvik Virtual Machine) rather than using JVM(Java Virtual Machine). DVM does not support byte-code.

23. What is a BuildType in Gradle?

Build Types define properties that Gradle uses when building and packaging an Android app.
A Build Type defines how a module will be built, for example, whether ProGuard is run.
A Product Flavour defines what is built, such as which resources are included in the build.
Gradle creates a build variant for every possible combination of the project’s Product Flavours and Build types. For Example:

buildType {
debug {}
release {}
productFlavors {
free {}
premium {}

Build variants created by Gradle (2*2 = 4):

  1. freeDebug
  2. freeRelease
  3. premiumDebug
  4. premiumRelease

24. Explain the build process in Android

There are multiple steps involved in the Android Build process:
Step 1:
Compiling the resources folder (/res) using the AAPT (Android Asset Packaging Tool). These are compiled to a single class file called R.java which contains only constants.
Step 2:
The java source code is compiled to .class files by javac
Step 3:
The class files are then converted to Dalvik byte-code by the “dx” tool, which is included in the SDK ‘tools’. The output is classes.dex.
Step 4:
The android apkbuilder takes all the input and builds the APK (Android Packaging Key) file.

25. What are Handlers?

Handlers are objects to manage threads or to communicate between threads, most commonly to pass an action from a background thread to Android’s main thread.
They run outside of the Activity’s lifecycle and thus need to be cleaned up properly or else we will have thread leaks.
A Handler class is preferred when we need to perform a background task repeatedly at regular intervals.

26. What is Job Scheduling?

Job Scheduling allows to schedule jobs while delegating the work of optimising memory, power, and connectivity conditions to the system.
The JobScheduler supports batch scheduling of jobs.
The Android system has the power to combine jobs, so that battery consumption is reduced.
JobManager makes handling uploads easier as it automatically handles the unreliability of the network.
It also survives application restarts.

It can render different scenarios like:

  • Tasks that should be done once the device is connected to a power supply
  • Tasks that require network access or a Wi-Fi connection
  • Tasks that are not critical or user-facing
  • Tasks that should regularly be running as a batch where the timing is not critical

27. How to clear the back stack of Activities when a new Activity is called using intent?

There are two ways:


28. What is the difference between FLAG_ACTIVITY_CLEAR_TASK and FLAG_ACTIVITY_CLEAR_TOP?

FLAG_ACTIVITY_CLEAR_TASK is used to clear all the activities from the task including any existing instances of the Activity invoked. The Activity launched by the intent becomes the new root of the empty task list. This flag has to be used in conjunction with FLAG_ACTIVITY_NEW_TASK.
FLAG_ACTIVITY_CLEAR_TOP if set and if an old instance of the called Activity exists in the task list then except that particular Activity, all the other activities are removed, and that old Activity becomes the root of the task list.
In a situation when there is no instance of the called Activity, then a new instance of the same is made the root of the task list.
Using FLAG_ACTIVITY_NEW_TASK in conjunction is a good practice, though not necessary.

29. What is the onTrimMemory() method?

Android can reclaim memory for from our app in several ways or even kill our app if necessary to free up memory for critical tasks.
This method (onTrimMemory) is called when the operating system has determined that it is a good time for a process to trim unused or extra memory from its process.
This may happen when the app goes to background, and there is not enough memory to keep since many background processes are running.
To help balance the system memory and avoid the system’s need to kill our app process, we can implement the ComponentCallbacks2 interface in our Activity classes. The provided onTrimMemory() callback method allows our app to listen for memory related events when our app is in either the foreground or the background, and then release objects in response to app lifecycle or system events that indicate the system needs to reclaim memory.

30. What is an Intent?

Intents are messages that can be used to pass information to the various components of the Android system.
Two types of Intents:

  • Implicit: It is when we call system default intent like send email, send SMS, dial number.
  • Explicit: It is when we call an Activity from another Activity of the same application.

31. What is a Sticky Intent?

Sticky Intents allows communication between a function and a service. sendStickyBroadcast() performs a sendBroadcast(Intent) known as sticky, i.e. the Intent we 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).
For example, if we take an intent for ACTION_BATTERY_CHANGED to get battery change events: When we call registerReceiver() for that action — even with a null BroadcastReceiver — we get the Intent that was the last broadcast for that action. Hence, we can use this to find the state of the battery without necessarily registering for all future state changes in the battery.

32. What is a Pending Intent?

If we want someone to perform any Intent operation at a future point of time on behalf of us, then we will use Pending Intent.

33. What are the Launch modes in Android?

Standard: It creates a new instance of an Activity in the task from which it was started. Multiple instances of the Activity can be created, and multiple instances can be added to the same or different tasks. 

Example: Suppose there is an Activity stack of:
A -> B -> C
Now, if we relaunch B with the launch mode as “standard”, the new stack will be:
A -> B -> C -> B

SingleTop: It is the same as the standard, except if there is a previous instance of the Activity that exists in the top of the stack, then it will not create a new instance but rather send the intent to the existing instance of the Activity.

Example: Suppose there is an Activity stack of:
A -> B
Now if we launch C with the launch mode as “singleTop”, the new stack will be:
A -> B -> C 
If we relaunch C with the launch mode as “singleTop”, the new stack will still be:
A -> B -> C

SingleTask: A new task will always be created, and a new instance will be pushed to the task as the root one. So if the Activity is already in the task, the intent will be redirected to onNewIntent() else a new instance will be created. At a time only one instance of Activity will exist.

Example: Suppose there is an Activity stack of:
A -> B -> C -> D
Now if we launch D with the launch mode as “singleTask”, the new stack will be:
A -> B -> C -> D
If we launch Activity B again with the launch mode as “singleTask”, the new Activity stack will be:
A -> B
Activities C and D will be destroyed.

SingleInstance: Same as singleTask but the system does not launch any activities in the same task as this Activity. If new activities are launched, they are done so in a separate task.

Example: Suppose there is an Activity stack of:
A -> B -> C
State of Activity Stack after launching D Activity
Task1:  A -> B -> C
Task2:  D (here D will be in a different task)
If we now launch Activity B again with the launch mode as “singleInstance”, the new Activity stack will be: 
Task1:  A -> B -> C
Task2:  D

34. Difference between Serializable and Parcelable?

Serialization is the process of converting an object into a stream of bytes in order to store an object into memory. This object can be recreated at a later time while still keeping the object’s original state and data.
Serializable is a standard Java interface.
Parcelable is an Android-specific interface where we can implement the serialization ourselves. It was created to be far more efficient than Serializable.
The problem with serialization is that it uses reflection and thus slows down the process. This mechanism also tends to create a lot of temporary objects and cause quite a bit of garbage collection.

35. Difference between adding/replacing Fragment in Backstack?

Replace Fragment: removes the existing Fragment and adds a new Fragment. This means when we press back button the Fragment that got replaced will be created with its onCreateView() being invoked.
Add Fragment: retains the existing Fragments and adds a new Fragment on top of the previous one. This indicates that the existing Fragment will be active and they won’t be in ‘paused’ state. Hence when a back button is pressed onCreateView() is not called for the existing Fragment placed below.

Here is a good reference for the same.

In terms of Fragment’s life cycle events; onPause(), onResume(), onCreateView() and other life cycle events will be invoked in case of Replace, but they won’t be invoked in case of Add.

36. When replacing one Fragment with another,  how do we ensure that the user can return to the previous Fragment by pressing the Back button?

We need to save each Fragment transaction to the back stack, by calling addToBackStack() before we commit() that transaction.

37. Why is it recommended to use only the default constructor to create a Fragment?

The Android OS has the power to restore a Fragment during any configuration changes (like orientation) by restoring the bundle in the Fragment. If we pass the Bundle rather than the arguments in the constructor, we are guaranteed to restore the state of the Fragment correctly to the same state it was initialised with earlier.

38. What are Retained Fragments?

By default, Fragments are destroyed and recreated along with their parent Activity’s when a configuration change occurs.
Calling setRetainInstance(true) allows us to bypass this destroy-and-recreate cycle. This call notifies the system to retain the current instance of the Fragment when the Activity is recreated.

39. What is Toast in Android?

A Toast can be used to display information for a short period. It contains a message to be displayed quickly and disappears after a finite interval.

40. Difference between Margin and Padding?

Padding will be space added inside the container; for instance, if it is a button, padding will be added inside the button.
A margin is a space added outside the container.

41. What is View Group? How are they different from Views?

View: It is the basic building blocks of User Interface(UI) elements in Android. A View is a simple rectangle box that responds to the user’s actions. Some examples of views are EditText, Button, CheckBox etc.
The View refers to the android.view.View class, which is the base class of all UI classes.
ViewGroup: ViewGroup is the invisible container. It holds View and ViewGroup. For example, LinearLayout is the ViewGroup that contains Button(View), and other Layouts also. ViewGroup is the base class for Layouts.

42. Difference between RelativeLayout and LinearLayout?

Linear Layout: Arranges elements either vertically or horizontally. i.e. in a row or column.
Relative Layout: Arranges elements relative to the parent or other components.

43. What is ConstraintLayout?

It allows us to create large and complex layouts with a flat view hierarchy (no nested view groups). It’s similar to RelativeLayout in that all views are laid out according to relationships between sibling views and the parent layout, but it’s more flexible than RelativeLayout and easier to use with Android Studio’s Layout Editor.

44. When can we use a FrameLayout?

Frame Layouts are designed to contain a single item, making them an efficient choice when we need to display a single View.
If we add multiple Views to a FrameLayout then it’ll stack them one above the other, so FrameLayouts are also useful if we need overlapping Views, for example, if we are implementing an overlay or a HUD element.

45. What is the difference between commit() and apply() in SharedPreferences?

commit(): it writes the data synchronously and returns a boolean value of success or failure depending on the result immediately.
apply(): it is asynchronous, and it will not return any boolean response.
Additional: If we have an apply() outstanding and we perform another commit(), the commit() will be blocked until the apply() is not completed.

46. What is the relationship between the life cycle of an AsyncTask and an Activity? What problems can result in this?

An AsyncTask is not tied to the lifecycle of the Activity that contains it. So, for example, if we start an AsyncTask inside an Activity and the user rotates the device, the Activity will be destroyed (and a new Activity instance will be created) but the AsyncTask will not die but instead goes on living until it completes.
Now, when the AsyncTask does complete, rather than updating the UI of the new Activity, it updates the former instance of the Activity (i.e., the one in which it was created, but that is not displayed anymore). This can lead to an Exception (of type java.lang.IllegalArgumentException: View not attached to window manager if you use, for instance, findViewById to retrieve a view inside the Activity).
There’s also the potential for this to result in a memory leak since the AsyncTask maintains a reference to the Activity, which prevents the Activity from being garbage collected as long as the AsyncTask remains alive.
For these reasons, using AsyncTasks for long-running background tasks is generally a bad idea. Preferably, for long-running background tasks, a different mechanism (such as a service) should be employed.
Note: AsyncTasks by default run on a single thread using a serial executor, meaning it has only one thread and each task runs one after the other.

47. What is the significant difference between ListView and RecyclerView?

There is a major difference between ListView and RecyclerView:
The ViewHolder pattern is entirely optional in ListView, but it is embedded into RecyclerView.
ListView only supports vertical scrolling, but RecyclerView supports both vertically and horizontally scrolling lists.

48. What is a ThreadPool? Is it more effective than using several separate Threads?

Creation and destruction of threads have a high CPU usage. When we need to perform lots of short, simple tasks concurrently, the overhead of creating our own threads can take up a significant portion of the CPU cycles and severely affect the response time.
ThreadPool consists of a task queue and a group of worker threads, which allows it to run multiple parallel instances of a task.

49. How would we update the UI of an Activity from a background service?

We need to register a Local BroadcastReceiver in the Activity and send a broadcast with the data using intents from the background service. As long as the Activity is in the foreground, the UI will be updated from the background.
Note: Ensure to unregister the broadcast receiver in the onStop() method of the Activity to avoid memory leaks. We can also register a Handler and pass data using Handlers.

50. What are Intent Filters?

An intent filter specifies the types of intents to which an Activity, service, or broadcast receiver can respond to by declaring the capabilities of a component. Android components register intent filters either statically in the AndroidManifest.xml or in case of a broadcast receiver also dynamically via code.

51. When should we use a Fragment rather than an Activity?

  • When we have UI components that are going to be used across multiple activities
  • When multiple views can be displayed side by side (viewPager tabs)
  • When we have data that needs to be persisted across Activity restarts (such as retained Fragments)

52. What are Loaders in Android?

Loader API, introduced in API level 11 (Android 3.0) is used to load data from a data source to display in an Activity or Fragment.
Loaders solve these problems and include other benefits. For example:

  • Loaders run on separate threads to prevent janky or unresponsive UI.
  • Loaders simplify thread management by providing callback methods when events occur.
  • Loaders persist and cache results across configuration changes to prevent duplicate queries.
  • Loaders can implement an observer to monitor for changes in the underlying data source. For example, CursorLoader automatically registers a ContentObserver to trigger a reload when data changes.

53. What is the difference between Dialog & DialogFragment?

Dialog is a small window that prompts the user to make a decision or enter additional information. A Dialog does not fill the screen and is usually used for modal events that require users to take action before they can proceed.
Dialogs are entirely dependent on the host Activity. If the screen is rotated, the Dialog will be dismissed. Dialog Fragments take care of orientation and configuration changes as well.

54. How do we create a custom view?

  • Create a class that Subclass a View
  • Create a res/values/attrs.xml file and declare the attributes we want to use with our custom View.
  • In our View class, we need to add a constructor method, instantiate the Paint object, and retrieve our custom attributes.
  • Override either onSizeChanged() or onMeasure().
  • Draw our View by overriding onDraw()

55. What are the permission protection levels in Android?

  • Normal — 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.
  • Dangerous — A higher-risk permission. 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 — A permission that the system grants only to applications that are in the Android system image or that are signed with the same certificate as the application that declared the permission

Useful resources:



Please follow and like: