Android Interview Questions & Answers


What is Android?Android is a software stack for mobile devices that includes an operating system, middleware and key applications.Google Inc. purchased the initial developer of the software, Android Inc., in 2005.Android's mobile operating system is based on the Linux kernel.

-----------------------------------------------------------------------------------
What are the different Android flavors?
The names of the first Android operating system since its launch from the Cupcake (Android 1.5),Donut (Android 1.6), Eclair (Android 2.1), Froyo (Android 2.2), Gingerbread (Android 2.3), and special tablets OS, Honeycomb (Android 3.0.), Ice Cream (Android 4.0), Jelly Bean (Android 4.1) , Kitkat (Android 4.4), Lollipop (Android 5.X), Marshmallow (Android 6.X), Nougat (Android 7.X) ,Oreo (Android 8), Pie (Android 9), Android Q.
 -----------------------------------------------------------------------------------
ADT Tools from DDMS perspective:-The Android Emulator: An implementation of the Android virtual machine designed to run on your development computer. You can use the emulator to test and debug your android applications.
-Dalvik Debug Monitoring Service (DDMS): Use the DDMS perspective to monitor and control the Dalvik virtual machines on which you’re debugging your applications. 
- Android Asset Packaging Tool (AAPT): Constructs the distributable Android package files (.apk). 
- Android Debug Bridge (ADB): The ADB is a client-server application that provides a link to a running emulator. It lets you copy files, install compiled application packages (.apk), and run shell commands.
-SQLite3: A database tool that you can use to access the SQLite database fi les created and used by Android. 
-Traceview: Graphical analysis tool for viewing the trace logs from your Android application 
-MkSDCard: Creates an SDCard disk image that can be used by the emulator to simulate an external storage card. 
-dx Converts Java .class bytecode into Android .dex bytecode. 
- activityCreator: Script that builds Ant build fi les that you can then use to compile your Android applications without the ADT plug-in.
-----------------------------------------------------------------------------------
What are some restrictions to keep in mind when creating new applications?
Low processing power,
Limited RAM,
Limited permanent storage capacity,
Small screens with low resolution,
Higher costs associated with data transfer,
Slower data transfer rates with higher latency,
Less reliable data connections,
Limited battery life.
-----------------------------------------------------------------------------------
What are the building blocks of an Android application?
- Activities: It is the application’s presentation layer. Every screen in your application will be an extension of the Activity class.
-Services:Service components run invisibly, updating your data sources and visible Activities and triggering Notifications. They’re used to perform regular processing that needs to continue even when your application’s Activities aren’t active or visible.
- Content Providers: A shareable data store. Content Providers are used to manage and share application databases. Content Providers are the preferred way of sharing data across application boundaries.
- Intents: A simple message-passing framework. Using Intents, you can broadcast messages system-wide or to a target Activity or Service, stating your intention to have an action performed. The system will then determine the target(s) that will perform any actions as appropriate.
- Broadcast Receivers: Intent broadcast consumers. By creating and registering a Broadcast Receiver, your application can listen for broadcast Intents that match specific filter criteria. Broadcast Receivers will automatically start your application to respond to an incoming Intent, making them ideal for event-driven applications.
- Notifications: Notifications let you signal users without stealing focus or interrupting their current Activities. They’re the preferred technique for getting a user’s attention from within a Service or Broadcast Receiver. For example, when a device receives a text message or an incoming call, it alerts you by flashing lights, making sounds, displaying icons, or showing dialog messages.
-----------------------------------------------------------------------------------
Explain the Android System Architecture.
  -----------------------------------------------------------------------------------
Explain the Android Application Architecture.
- Activity Manager: Controls the life cycle of your activities, including management of the activity stack.
-Views Are used to construct the user interfaces for your activities.
- Notification Manager: Provides a consistent and non-intrusive mechanism for signaling your users.
- Content Providers: Lets your applications share data between applications.
- Resource Manager: Supports non-code resources like strings and graphics to be externalized. 
 -----------------------------------------------------------------------------------  
Explain the Android Application LifeCycle.
Android applications have no control over their own life cycles. Instead, application components must listen for changes in the application state and react accordingly.


onCreate() :
Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one. Always followed by onStart().
onRestart() :
Called after your activity has been stopped, prior to it being started again. Always followed by onStart()
onStart() :
Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.
onResume() :
Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it. Always followed by onPause().
onPause ():
Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume(). When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A's onPause() returns, so be sure to not do anything lengthy here.
onStop():
Called when you are no longer visible to the user. You will next receive either onRestart(), onDestroy(), or nothing, depending on later user activity.
Note that this method may never be called, in low memory situations where the system does not have enough memory to keep your activity's process running after its onPause() method is called.
onDestroy() :
The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.
Note:
When the Activity first time loads the events are called as below:
onCreate()
onStart()
onResume()
When you click on Phone button the Activity goes to the background & below events are called:
onPause()
onStop()
Exit the phone dialer & below events will be called:
onRestart()
onStart()
onResume()
When you click the back button OR try to finish() the activity the events are called as below:
onPause()
onStop()
onDestroy()
---
The order in which processes are killed to reclaim resources is determined by the priority of the hosted applications. In Android, all applications will remain running and in memory until the system needs its resources for other applications.
Active Processes: Active (foreground) processes are those hosting applications with components currently interacting with the user. These are the processes Android is trying to keep responsive by reclaiming resources. There are generally very few of these processes, and they will be killed only as a last resort.
-Visible Processes: Visible, but inactive processes are those hosting “visible” Activities. As the name suggests, visible Activities are visible, but they aren’t in the foreground or responding to user events. This happens when an Activity is only partially obscured (by a non-full-screen or transparent Activity). There are generally very few visible processes, and they’ll only be killed in extreme circumstances to allow active processes to continue.
- Started Service Processes: Processes hosting Services that have been started. Services support ongoing processing that should continue without a visible interface. Because Services don’t interact directly with the user, they receive a slightly lower priority than visible Activities. They are still considered to be foreground processes and won’t be killed unless resources are needed for active or visible processes.
- Background Processes: Processes hosting Activities that aren’t visible and that don’t have any Services that have been started are considered background processes. There will generally be a large number of background processes that Android will kill using a last-seen-first-killed pattern to obtain resources for foreground processes.
-Empty Processes: To improve overall system performance, Android often retains applications in memory after they have reached the end of their lifetimes. Android maintains this cache to improve the start-up time of applications when they’re re-launched. These processes are routinely killed as required.
-----------------------------------------------------------------------------------
Explain the Android Service LifeCycle.



-----------------------------------------------------------------------------------
Explain the Android Fragment LifeCycle.



-----------------------------------------------------------------------------------
Describe the APK format.
The APK file is compressed file consisting of the AndroidManifest.xml file, application code (.dex files), resource files, and other files. A project is compiled into a single .apk file.
-----------------------------------------------------------------------------------
What is an action? A description of something that an Intent sender desires.
-----------------------------------------------------------------------------------
What is activity? A single screen in an application, with supporting Java code.
-----------------------------------------------------------------------------------
What is intent? A class (Intent) describes what a caller desires to do. The caller sends this intent to Android's intent resolver, which finds the most suitable activity for the intent. E.g. opening a PDF file is an intent, and the Adobe Reader is the suitable activity for this intent.
-----------------------------------------------------------------------------------
How is nine-patch image different from a regular bitmap?
It is a resizable bitmap resource that can be used for backgrounds or other images on the device. The NinePatch class permits drawing a bitmap in nine sections. The four corners are unscaled; the four edges are scaled in one axis, and the middle is scaled in both axes.
-----------------------------------------------------------------------------------
What languages does Android support for application development?
Android applications are written using the Java and/or Kotlin programming languages.
-----------------------------------------------------------------------------------
How will you record a phone call in Android? How to get a handle on Audio Stream for a call in Android?

Permissions.PROCESS_OUTGOING_CALLS: Allows an application to monitor, modify, or abort outgoing calls.
-----------------------------------------------------------------------------------
What's the difference between file, class and activity in android?
File - It is a block of arbitrary information, or resource for storing information. It can be of any type.
Class - Its a compiled form of .Java file . Android finally used this .class files to produce an executable apk
Activity - An activity is the equivalent of a Frame/Window in GUI toolkits. It is not a file or a file type it is just a class that can be extended in Android for loading UI elements on view.
-----------------------------------------------------------------------------------
What is a Sticky Intent?
sendStickyBroadcast() performs a sendBroadcast (Intent) that is "sticky," i.e. 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).

One example of a sticky broadcast sent via the operating system is ACTION_BATTERY_CHANGED. When you call registerReceiver() for that action -- even with a null BroadcastReceiver -- you get the Intent that was last broadcast for that action. Hence, you can use this to find the state of the battery without necessarily registering for all future state changes in the battery.
-----------------------------------------------------------------------------------
-Remember that the GUI layer doesn't request data directly from the web; data is always loaded from a local database. The service layer periodically updates the local database.
----------------------------------------------------------------------------------- 
What is the risk in blocking the Main thread when performing a lengthy operation such as web access or heavy computation? Application_Not_Responding exception will be thrown which will crash and restart the application.
-----------------------------------------------------------------------------------
Difference between MVP & MVC

Here are the key differences between MVC and MVP:


-----------------------------------------------------------------------------------
Why is List View not recommended to have active components? Clicking on the active text box will pop up the software keyboard but this will resize the list, removing focus from the clicked element.
-----------------------------------------------------------------------------------
What are the exceptions that are supported by Android? 
InflateException : When an error conditions are occurred, this exception is thrown
Surface.OutOfResourceException: When a surface is not created or resized, this exception is thrown
SurfaceHolder.BadSurfaceTypeException: This exception is thrown from the lockCanvas() method, when invoked on a Surface whose is SURFACE_TYPE_PUSH_BUFFERS
WindowManager.BadTokenException: This exception is thrown at the time of trying to add view an invalid WindowManager.LayoutParamstoken.
-----------------------------------------------------------------------------------
When to use a service?
It is an ability for the application to tell the system about something it wants to be doing in the background (This corresponds to calls to Context.startService(), which ask the system to schedule work for the service, to be run until the service or someone else explicitly stop it.  It is also a facility for an application to expose some of its functionality to other applications. This corresponds to calls to Context.bindService(), which allows a long-standing connection to be made to the service in order to interact with it.
-----------------------------------------------------------------------------------
Name some views in Android.
-TextView: A standard read-only text label. It supports multiline display, string formatting, and automatic word wrapping.
 -EditText: An editable text entry box. It accepts multiline entry, word-wrapping, and hint text.
-ListView: A View Group that creates and manages a vertical list of Views, displaying them as rows within the list. The simplest List View displays the toString value of each object in an array, using a Text View for each item.
- Spinner: A composite control that displays a Text View and an associated List View that lets you select an item from a list to display in the textbox. It’s made from a Text View displaying the current selection, combined with a button that displays a selection dialog when pressed.
- Button: A standard push-button.
-CheckBox: A two-state button represented by a checked or unchecked box.
-RadioButton: A two-state grouped button. A group of these presents the user with a number of binary options of which only one can be enabled at a time.
-ViewFlipper: A View Group that lets you define a collection of Views as a horizontal row in which only one View is visible at a time, and in which transitions between visible views are animated.
-QuickContactBadge: Displays a badge showing the image icon assigned to a contact you specify using a phone number, name, e-mail address, or URI. Clicking the image will display the quick contact bar, which provides shortcuts for contacting the selected contact—including calling, sending an SMS, e-mail, and IM.
-----------------------------------------------------------------------------------
What are the different types of Layouts in Android?
Layout managers are extensions of the ViewGroup class used to position child controls for your UI. Layouts can be nested, letting you create arbitrarily complex interfaces using a combination of layouts.

-FrameLayout: The simplest of the Layout Managers, the Frame Layout simply pins each child view to the top left corner. Adding multiple children stacks each new child on top of the one before, with each new View obscuring the last.
-LinearLayout: A Linear Layout aligns each child View in either a vertical or a horizontal line. A vertical layout has a column of Views, while a horizontal layout has a row of Views. The Linear Layout manager enables you to specify a ‘‘weight’’ for each child View that controls the relative size of each within the available space.
- RelativeLayout: The most flexible of the native layouts, the Relative Layout lets you define the positions of each child View relative to the others and to the screen boundaries.
-TableLayout: The Table Layout lets you lay out Views using a grid of rows and columns. Tables can span multiple rows and columns, and columns can be set to shrink or grow.
- Gallery: A Gallery Layout displays a single row of items in a horizontally scrolling list.
CoordinatorLayout: It is an enhanced version of the Frame Layout introduced in Android Lollipop through the material design. is described as a “a super-powered FrameLayout” according to the docs. It is used to facilitate how views within your layout interact with each other.
AppBarLayout : AppBarLayout is a vertical LinearLayout that is generally the first child inside a CoordinatorLayout and acts as a wrapper for the ToolBar in most cases. Using the ToolBar as a direct child of CoordinatorLayout would work fine but it will not be able to coordinate with other child views present. Here’s where the importance of AppBarLayout arises.
 -----------------------------------------------------------------------------------
What are the different types of Fragments in Android?
- Single Frame Fragment
- Dialog Fragment
- List Fragment
- Preference Fragment -----------------------------------------------------------------------------------
What is a resource?
A user-supplied XML, bitmap, or other file, injected into the application build process, which can later be loaded from code.
 -----------------------------------------------------------------------------------
Name some drawable resources.
Drawables: Color,Shape,Gradient, Composite, Transformative, Layer, State List, LevelList, NinePatch
 -----------------------------------------------------------------------------------
What are Menus?
Menus offer a way to expose application functions without sacrificing valuable screen space.
-The icon menu appears along the bottom of the screen when the menu button is pressed. It displays the icons and text for a limited number of Menu Items (typically six). This icon menu does not display checkboxes, radio buttons, or the shortcut keys for MenuItems.
If the Activity menu contains more than the maximum number of visible Menu Items, a More Menu Item is displayed. When selected, it displays the expanded menu. Pressing the back button closes the icon menu.
-The expanded menu The expanded menu is triggered when a user selects the More Menu Item from the icon menu. It displays a scrollable list of only theMenu Items that weren’t visible in the icon menu. This menu displays full text, shortcut keys, and checkboxes/radio buttons. It does not, however, display icons. Pressing back from the expanded menu returns you to the icon menu.
Submenus The traditional expanding hierarchical tree can be awkward to navigate using a mouse, so it’s no surprise that this metaphor is particularly ill-suited for use on mobile devices. The Android
alternative is to display each submenu in a floating window.
 -----------------------------------------------------------------------------------
What are intents?
It is a simple message-passing framework. Using Intents, you can broadcast messages system-wide or to a target Activity or Service, stating your intention to have an action performed. The system will then determine the target(s) that will perform any actions as appropriate.
Intents can be used to:
- Declare your intention that an Activity or Service be started to perform an action, usually with (or on) a particular piece of data.
- Broadcast that an event (or action) has occurred.
- Explicitly start a particular Service or Activity.
 -----------------------------------------------------------------------------------
Describe Adapters.Adapters are bridging classes that bind data to Views (such as List Views) used in the user interface. The adapter is responsible for creating the child Views used to represent each item within the parent View, and providing access to the underlying data. Views that support Adapter binding must extend the AdapterView abstract class.
ListAdapter,ArrayAdapter,CursorAdapter,HeaderViewListAdapter,SourceCursorAdapter,SimpleAdapter,SpinnerAdapter
WrappedListAdapter.
 -----------------------------------------------------------------------------------
Explain Dialogs in Android.
Dialog boxes in Android are partially transparent, floating Activities that partially obscure theActivities that launched them.There are three ways to implement a dialog in Android: .
- Using the Dialog class: As well as the general-purpose AlertDialog class, Android includes a number of specialist classes that extend Dialog. Each is designed to provide specific dialog box functionality. A Dialog-class-based screen is constructed entirely within its calling Activity, so it doesn’t need to be registered in the manifest as its life cycle is controlled entirely by the calling Activity.
- Dialog-themed Activities: You can apply the dialog theme to a regular Activity to give it the appearance of a standard dialog box.
- Toasts: Toasts are special non-modal transient message boxes, often used by Broadcast Receivers and Services to notify users of events occurring in the background.
 -----------------------------------------------------------------------------------
Difference between Dialog and AlertDialog

This is something you can try on:

1.Create an EditText programmatically
2.Put the EditText into a layout and put all into an AlertDialog using
alertDialog.setView(layoutWithMyEditText);3.Touch the EditText to open the keyboard. It won't work 
This is how to fix it: Instead of AlertDialog, use the Dialog class.
dialog.setContentView(layoutWithMyEditText)
This is why it works:
AlertDialog is a lightweight version of a Dialog. This is supposed to deal with INFORMATIVE matters only, That's the reason why complex interaction with the user is limited. In the other hand, Dialog includes all the features we're expecting .
-----------------------------------------------------------------------------------
The Preference Activity framework consists of three parts:
- Preference Screen Layout: An XML file that defines the hierarchy displayed in your Preference Activity. It specifies the controls to display, the values to allow, and the Shared Preference keys to use for each UI control.
-Preference Activity: An extension of PreferenceActivity that will be used to host your application preference screens.
- Shared Preference Change Listener: An implementation of the onSharedPreferenceChangeListener class used to listen for changes to Shared Preferences.
 -----------------------------------------------------------------------------------
Native Preference Controls:
Android includes several preference controls to build your Preference Screens:
- CheckBoxPreference: A standard preference checkbox control. Used to set preferences to true or false.
- EditTextPreference: Allows users to enter a string value as a preference. Selecting the preference text will display a text entry dialog.
- ListPreference: The preference equivalent of a spinner. Selecting this preference will display a dialog
box containing a list of values from which to select. You can specify different arrays to contain the display text and selection values.
- RingtonePreference: A specialized List Preference that presents the list of available ringtones for user selection. This is particularly useful when you’re constructing a screen to configure notification settings.
 -----------------------------------------------------------------------------------
What are Content Providers?
Content Providers offer a generic interface to any data source by decoupling the data storage layer from the application layer. Content Providers offer a standard interface your applications can use to share data with and consume data from other applications— including many of the native data stores.  -----------------------------------------------------------------------------------
What are cursors & Content Values?
ContentValues are used to insert new rows into tables. Each Content Values object represents a single
table row as a map of column names to values.

Queries in Android are returned as Cursor objects. Rather than extracting and returning a copy of the result values, Cursors are pointers to the result set within the underlying data. Cursors provide a managed way of controlling your position (row) in the result set of a database query.
 -----------------------------------------------------------------------------------
What are Android Permissions?Permissions are an application-level security mechanism that lets you restrict access to application components. Permissions are used to prevent malicious applications from corrupting data, gaining access to sensitive information, or making excessive (or unauthorized) use of hardware resources or external communication channels.
The native permission strings used by native Android Activities and Services can be found as static constants in the android.Manifest.permission class. To use permission-protected components, you need to add <uses-permission> tags to application manifests, specifying the permission string that each application requires. When an application package is installed, the permissions requested in its manifest are analyzed and granted (or denied) by checks with trusted authorities and user feedback.
 -----------------------------------------------------------------------------------
Describe Notifications.
Notifications are used to alert users without using an Activity. Using Notifications is the preferred way for invisible application components (Broadcast Receivers, Services, and inactive Activities) to alert users that events have occurred that may require attention.
Currently they have the ability to:
- Create new status bar icons
- Display additional information (and launch an Intent) in the extended status bar window
- Flash the lights/LEDs
- Vibrate the phone
- Sound audible alerts (ringtones, Media Store audio)

 -----------------------------------------------------------------------------------
What are the different Push Notification Frameworks used in Android over the years?

1. C2DM:  Cloud to Device Messaging was officially deprecated on June 26, 2012, and was shut down completely as of July 30, 2015.
2. GCM:  Google Cloud Messaging was officially deprecated on May 29, 2019, and was shut down completely as of July 30, 2015.
3. FCM: Firebase Cloud Messaging (FCM) is a cross-platform messaging solution from Google that lets you reliably deliver messages at no cost.
 -----------------------------------------------------------------------------------
Bundle are used for passing data between various Activities. It depends on you what type of values you want to pass but bundle can hold all types of values and pass to the new activity.You can use it like:
Intent intent = new Intent(getApplicationContext(),SecondActivity.class);
intent.putExtra("myKey",AnyValue);  
startActivity(intent);

Now you can get the passed values by...
Bundle extras = intent.getExtras(); String tmp = extras.getString("myKey");

-----------------------------------------------------------
What is a Android App Bundle?

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

Google Play’s new app serving model, called Dynamic Delivery, then uses your app bundle to generate and serve optimized APKs for each user’s device configuration, so they download only the code and resources they need to run your app. You no longer have to build, sign, and manage multiple APKs to support different devices, and users get smaller, more optimized downloads.  -----------------------------------------------------------
Why use the Android Manifest file?

Every application must have an AndroidManifest.xml file in its root directory. The manifest presents essential information about the application to the Android system, information the system must have before it can run any of the application's code. Among other things, the manifest does the following:
  • It names the Java package for the application. The package name serves as a unique identifier for the application.
  • It describes the components of the application — the activities, services, broadcast receivers, and content providers that the application is composed of. It names the classes that implement each of the components and publishes their capabilities (for example, which Intent messages they can handle). These declarations let the Android system know what the components are and under what conditions they can be launched.
  • It determines which processes will host application components.
  • It declares which permissions the application must have in order to access protected parts of the API and interact with other applications.
  • It also declares the permissions that others are required to have in order to interact with the application's components.
  • It lists the Instrumentation classes that provide profiling and other information as the application is running. These declarations are present in the manifest only while the application is being developed and tested; they're removed before the application is published.
  • It declares the minimum level of the Android API that the application requires.
  • It lists the libraries that the application must be linked against.  
-----------------------------------------------------------
What's onCreate(Bundle savedInstanceState)

If you save the state of the application in a bundle (typically non-persistent, dynamic data in onSaveInstanceState), it can be passed back to onCreate if the activity needs to be recreated (e.g., orientation change) so that you don't lose this prior information. If no data was supplied, savedInstanceState is null.

Suppose, you have a simple fragment or Activity with a TextView and a Button. Each time you clicked the button the text changes. Now, change the orientation of you device/emulator and notice that you lost the data (means the changed data after clicking you got) and fragment starts as the first time again. By using Bundle savedInstanceState we can get rid of this.

We can save the state means the changed text value into that bundle like this
 int counter  = 0;
 @Override
 public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("value",counter);
 }
After you make the orientation the "onCreate" method will be called. So we can just do this

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if(savedInstanceState == null){
        //it is the first time the fragment is being called
        counter = 0;
    }else{
        //not the first time so we will check SavedInstanceState bundle
        counter = savedInstanceState.getInt("value",0); //zero is default value
    }
}