Android interview questions and answers 👇
Is it possible to use or add a fragment without using a user interface?↑
Yes, it is possible. When you want to create a background behavior for a particular activity. You can do this by using add(Fragment,string) method to add a fragment from the activity.
What are the Default Resources? How are they useful?↑
The Default resources include the default strings and files. Their absence will result in creating errors on the screen and could also hinder the running of the downloaded application. They are useful as they are placed as subdirectories under the project directory, which supports the running of the downloaded application.
What is Adapter in Android?↑
The adapter, as the name suggests is based on the concept of inheritance. Using the Adapter, you can create a child view on Android to present the items in the parent view.
What is the difference between Service and IntentService?↑
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 so it 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 longer 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. Writing an IntentService can be quite simple; just extend the IntentService class and override the onHandleIntent(Intent intent) method where you can manage all incoming requests.
What are the troubleshooting techniques you can follow if an application is crashing frequently?↑
If an Android application is crashing frequently, you can follow the below-given techniques:
- It is not possible to test an application for all kinds of devices and operating systems. There might be a possibility that an application is not compatible with your OS.
- Some apps run perfectly on one mobile device but might crash on other devices. This is where processing power, memory management, and CPU speed are considered.
- As there is a limited amount of memory space on mobile devices, you can free up memory space for the application to function properly.
- If an application is frequently crashing, you can delete the application’s data, which will clear its cache memory and allow some free space on your device and might boost the app’s performance.
What is a Sticky Intent?↑
A Sticky Intent is a broadcast from sendStickyBroadcast() method such that the intent floats around even after the broadcast, allowing others to collect data from it.
What are the core building blocks of android?↑
- Activity : An Activity is the screen representation of any application in Android. Each activity has a layout file where you can place your UI.
- Content Provider: Content providers share data between applications.
- Service: It is a component that runs in the background to perform long-running operations without interacting with the user and it even works if application is destroyed.
- Broadcast Receivers: It respond to broadcast messages from other applications or from the system itself. These messages are sometime called events or intents.
What is Constraint Layout in Android?↑
ConstraintLayout combines a simple, expressive and flexible layout system with the powerful features built into the Android Studio Designer tool. It makes it easier to create responsive user interface layouts that adapt automatically to different screen sizes and changing device orientations.
What is a Singleton Class in Android?↑
A singleton class in Android is a class that can only instantiate one object. This object can then be shared by all classes. An example could be of controlling concurrency and creating a central point of access for an application to access its data store.
How can an application perform actions that are provided by another application, e.g., sending an email?↑
Intents are created to define an action that we want to perform, and they launch the appropriate activity from another application.\
Which method is called only once in a fragment life cycle?↑
State some advantages of Android.↑
- Low investment and better returns: Android development has a low entry barrier and is suitable for new developers looking to become proficient in the programming field.
- Free SDK: One of the most prominent features of Android is that the Software Development Kit is open source and is provided free of charge, which eradicates the cost of licensing, distribution and development fee.
- Easy Adoption: Android applications are scripted in Java, which is one of the most used programming languages in the world.
- Reusable: Android components can be reused and even replaced by the framework.
- Multi-Platform Support: The Android platform supports major OSs such as Linux, Mac OS, and Windows.
- Support for Wearable Devices: The market is now flooded with wearable devices and Android has emerged as leading support for such devices that are now readily available in the market.
What is the relationship between the lifecycle of an AsyncTask and the lifecycle of an Activity? What problems can this result in, and how can these problems be avoided?↑
An AsyncTask is not tied to the lifecycle of the Activity that contains it. If the Activity is destroyed and a new instance of the Activity is created, the AsyncTask won’t be destroyed. This can lead to a number of problems, but the major ones an Android developer should be aware of are:
- Once the AsyncTask completes, it’ll try to update the former instance of the Activity, resulting in an IllegalArgumentException.
- Since the AsyncTask maintains a reference to the previous instance of the Activity, that Activity won’t be garbage collected, resulting in a memory leak.
The solution is to avoid using AsyncTasks for long-running background tasks.
What are the possible states in which a process is based?↑
The possible states in which a process is based include the following.
- State 1: Foreground activity
- State 2: Visible activity
- State 3: Background activity
- State 4: Empty activity
What are Services?↑
Service is an Android component that runs in the background and acts independently. It does not provide any user interface.
Though services are running behind the scene, a user can continue their work on different apps. Most of the time, the users are not aware of the services which are running in the background. These services allow the system to kill the process without interrupting the user’s ongoing work.
What is the database used for the Android platform?↑
SQLite is used for the Android platform. It is an open-source, serverless database.
What is the difference between iterator and enumeration in java?↑
- In Enumeration we don't have remove() method and we can only read and traverse through a collection.
- Iterators can be applied to any collection. In Iterator, we can read and remove items from a collection.
What is the difference between File, Class, and Activity in android?↑
- File is a block of arbitrary information or resources for storing information. It can be any file type.
- Class is a compiled from of .Java file which Android uses to produce an executable apk.
- Activity is the equivalent of a Frame/Window in GUI toolkits. It is not a file or a file type but just a class that can be extended in Android to load UI elements on view.
What is an Application Resource File?↑
Application resource files are files that include static content that your code can use. This includes layout definitions, bitmaps, animation instructions, user interface strings, and more.
Which dialog boxes supported by the Android platform?↑
Android supports four types of dialog boxes:
- AlertDialog: It has a maximum of 3 buttons and sometimes AlertDialog includes checkboxes and Radio buttons to select the element.
- ProgressDialog: It displays the progress bar or wheels.
- TimePickerDialog: Using this dialog box, a user selects the Time.
- DatePickerDialog: Using this dialog box, a user selects the Date
How can the ANR be prevented?↑
One technique that prevents the Android system from concluding a code that has been responsive for a long period of time is to create a child thread. Within the child thread, most of the actual workings of the codes can be placed, so that the main thread runs with minimal periods of unresponsive times.
What is an Adapter in Android?↑
An adapter in Android acts as a bridge between an AdapterView and the underlying data for that view. The adapter holds the data and sends the data to the adapter view, the view can take the data from the adapter view and shows the data on different views like a spinner, list view, grid view, etc.
How would you create a multi-threaded Android app without using the Thread class?↑
If you only need to override the run() method and no other Thread methods, then you should implement Runnable.
In particular, you should be on the lookout for an Android developer demonstrating an understanding that you should only extend from a class when you need to modify some of its functionality.
What is ActivityCreator?↑
ActivityCreator is a batch file and shell script which was used to create a new Android project. It is now replaced by the “Create New Project” in Android SDK.
Explain Activity Lifecycle.↑
When a user interacts with the app and moves here and there, out of the app, returns to the app, etc. During all this process “Activity” instances also move in the different stages in their lifecycle.
There are seven different states like – onCreate(), onStart(), onRestart(), onResume(), onPause(), onStop(), and onDestroy(). These are termed as a ‘callback’. Android system invokes these callbacks to know that the state has been changed.
When a user is working on an app, then there are many activities involved in it like Open, Close, Save, Delete, Send, etc.
Based on the user action these activities are partially disconnected from the UI but these activities always reside in the memory so that when the user calls back the same activity, the user will be in the same state where he has left off.
What is DDMS?↑
DDMS stands for Dalvik Debug Monitor Service. It is a debugging tool that comes with Android. It provides an array of services like port forwarding, screen capture, logcat process, thread and heap information on the device, radio state information, incoming call, SMS spoofing, and many more.
What is SnapHelper?↑
SnapHelper is a helper class that helps in snapping any child view of the RecyclerView. For example, you can snap the firstVisibleItem of the RecyclerView as you must have seen in the play store application that the firstVisibleItem will be always completely visible when scrolling comes to the idle position.
Explain the AndroidManifest.xml file and the need for it.↑
Every application must have an AndroidManifest.xml file in the root directory. It contains information about your app and provides the same to the Android system.
The information includes the package name, Android components such as Activity, Services, Broadcast Receivers, Content Providers, etc. Every Android system must have this information before running any app code.
AndroidManifest.xml file performs the following tasks:
- It provides a name to the Java package and this name is a unique identifier for the application.
- It describes the various components of the application which include Activity, Services, Content Providers, etc. Also, it defines the classes which implement these components.
- It is responsible to protect the application and it declares the permission for accessing the protected part of the app.
- It also declares the Android API which is going to be used by the application.
- It contains the library file details which are used and linked to the application.
When is the best time to kill a foreground activity?↑
The foreground activity, being the most important among the other states, is only killed or terminated as a last resort, especially if it is already consuming too much memory. When a memory paging state has been reach by a foreground activity, then it is killed so that the user interface can retain its responsiveness to the user.\
Explain Sensors in Android.↑
Android-based devices have a collection of built-in sensors in them, which measure certain parameters like motion, orientation, and many more through their high accuracy. The sensors can be both hardware and software based on nature. There are three prominent categories of sensors in Android devices. They are:
- Position Sensor: It is used for measuring the physical position of the Android device. This has orientation sensors and magnetometers.
- Motion Sensors: These sensors consist of gravity, rotational activity, and acceleration sensors which measure the rotation of the device or the acceleration, etc.
- Environmental Sensor: It includes sensors that measure temperature, humidity, pressure, and other environmental factors.
What are Configuration Changes and When Do They Happen?↑
Configuration changes cause Android to restart the activity. They include changes to screen orientation, keyboard availability and multi-window mode. When a configuration change occurs, you must issue a call to onDestroy(). You follow this with a call to onCreate().
Name the different data storage options available on the Android platform.↑
Android platform provides a variety of data storage options which can be used depending upon the need of the user. The storage options are:
- SharedPreference: This option stores data in XML files
- SQLite: This stores structured data in the private database
- Internal Storage: This stores data in the device file system where it cannot be read by other applications
- External Storage: This stores data in the file system but it can be accessed to all apps in the device
What is the difference between Parcelable and Serializable?↑
Serializable is a standard Java interface that’s easy to integrate into your app, as it doesn’t require any methods. Despite being easy to implement, Serializable uses the Java reflection API, which makes it a slow process that creates lots of temporary objects.
Parcelable is optimized for Android, so it’s faster than Serializable. It’s also fully customizable, so you can be explicit about the serialization process, which results in less garbage objects.
Name the resource that is a compiled visual resource, which can be used as a background, title, or in other parts of the screen.↑
Drawable is the virtual resource that can be used as a background, title, or in other parts of the screen. It is compiled into an android.graphics.drawable subclass. A drawable resource is a general concept for a graphic that can be drawn. The simplest case is a graphical file (bitmap), which would be represented in Android via a BitmapDrawable class.
Drawable is stored as an individual file in one of the res/drawable folders. The ADT project creation wizard creates these folders by default. You would store bitmaps for different resolutions in the -mdpi, -hdpi, -xhdpi, and -xxhdpi subfolders of res/drawable. If these bitmaps are provided in a different folder, the Android system selects the correct one automatically based on the device configuration.
What are the differences between abstract classes and interfaces?↑
- An abstract class, is a class that contains both concrete and abstract methods (methods without implementations). An abstract method must be implemented by the abstract class sub-classes. Abstract classes cannot be instantiated and need to be extended to be used.
- An interface is like a blueprint/contract of a class (or it may be thought of as a class with methods, but without their implementation). It contains empty methods that represent, what all of its subclasses should have in common. The subclasses provide the implementation for each of these methods. Interfaces are implemented.
When dealing with multiple resources, which one takes precedence?↑
Assuming that all of these multiple resources are able to match the configuration of a device, the 'locale' qualifier almost always takes the highest precedence over the others.
What is an Android Toast?↑
An Android toast is a small message that is displayed on top of the UI. It is a temporary message that acts like a tooltip. It helps in providing the user with feedback about the operation they are performing.
How can you pass data to sub-activities?↑
We can use bundles to pass data to sub-activities. There are HashMaps that take trivial data types. These bundles transport information from one activity to another.
Define and explain the Android Framework.↑
Android framework is a set of API’s using which the Android developers write code for the mobile apps. It contains the methods and classes to write the programming code.
Android framework includes a different set of tools to create image pane, text field, buttons, etc. It also includes “Activities” with which the user interacts and “Services”, which are the programs that run in the background. It is a package of different components like Intents, Broadcast Receivers, Content Providers, etc.
What’s the difference between onCreate() and onStart()?↑
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().
What is the major difference between ListView and RecyclerView?↑
- The ViewHolder pattern is entirely optional in ListView, but it’s baked into RecyclerView.
- ListView only supports vertical scrolling, but RecyclerView isn’t limited to vertically scrolling lists
How do you find memory leaks in an app on the Android platform?↑
Android Studio uses Android Device Manager (ADM). This ADM is used to detect the memory leaks in the Android platform.
When you open ADM in the Android Studio then on the left-hand side of the ADM, you will find your device or emulator in which a heap sign will be displayed. When you are running any mobile app then you will see the heap size, memory analysis and other statistics displayed on it.
What are the four essential states of an activity?↑
- Active: if the activity is at the foreground
- Paused: if the activity is at the background and still visible
- Stopped: if the activity is not visible and therefore is hidden or obscured by another activity
- Destroyed: when the activity process is killed or completed terminated
What are broadcast receivers? How are they implemented?↑
A broadcast receiver is a mechanism used for listening to system-level events like listening for incoming calls, SMS, etc. by the host application. It is implemented as a subclass of BroadcastReceiver class and each message is broadcasted as an intent object.
What is a Fragment?↑
Fragments in Android encapsulate views and logic so that it is easier to reuse within activities. Thus, using fragments we can display multiple screens on one activity. Fragments are a combination of XML layout files and a java class, making them very similar to activities.
Enumerate the steps in creating a bounded service through AIDL.↑
- create the .aidl file, which defines the programming interface
- implement the interface, which involves extending the inner abstract Stub class as well as implanting its methods.
- expose the interface, which involves implementing the service to the clients.
When should you use a Fragment, rather than an Activity?↑
This is still a much-debated topic, but the code used to create an Activity is fundamentally more involved than the code used to create a Fragment. The old Activity has to be destroyed, paused or stopped, and a new Activity has to be created. The developer should acknowledge that the best practice is to only use Activities when you need to swap the entire screen, and use fragments everywhere else.
In the following cases you’ll almost always use a Fragment, rather than an Activity:
- When you’re working with UI components or behavior that you’re going to use across multiple Activities.
- When you’re using one of the navigational methods that are closely linked to fragments, such as swipe views.
- When your users would benefit from seeing two different layouts side-by-side.
- When you have data that needs to persist across Activity restarts (i.e you need to use retained fragments).
What is the difference between a regular bitmap and a nine-patch image?↑
In general, a Nine-patch image allows resizing that can be used as background or other image size requirements for the target device. The Nine-patch refers to the way you can resize the image: 4 corners that are unscaled, 4 edges that are scaled in 1 axis, and the middle one that can be scaled into both axes.
What is a SpannableString?↑
A SpannableString has immutable text, but its span information is mutable. Use a SpannableString when your text doesn't need to be changed but the styling does. Spans are ranges over the text that include styling information like color, heighliting, italics, links, etc
When is the onStop() method invoked?↑
A call to onStop method happens when an activity is no longer visible to the user, either because another activity has taken over or if in front of that activity.
Explain the Architecture of an Android Application.↑
Android app development typically follows the Model-View-Presenter (MVP) architecture. Here, the Model is the data layer, the View is the UI layer, and the Presenter responds to actions performed by the UI layer.
Android app components include:
- Services that are used to initiate background tasks
- Intent is what creates the connection between activities and data passing.
- Notification in form of light, sound, dialog boxes, etc
- Content providers to share data between apps
- Resource externalization for strings and graphics
What is the use of an activityCreator?↑
An activityCreator is the first step towards the creation of a new Android project. It is made up of a shell script that will be used to create new file system structure necessary for writing codes within the Android IDE.
What is a Service?↑
A service in android is a background process which is used to perform long-running operations. Let’s say, a service of location is active in the background while the user is in a different application. So it does not disturb the user interaction with an activity. Now, services are classified into two types, namely:
- Local: This service is accessed from within the application.
- Remote – This service is accessed remotely from other applications running on the same device.
What are the exceptions in Android?↑
- InflateException: When error conditions occur this exception is thrown.
- Surface.OutOfResourceException: When a Surface is not created or resized, this exception is thrown.
- SurfaceHolder.BadSurfaceTypeException: When invoked on a Surface ‘SURFACE_TYPE_PUSH_BUFFERS’, this exception is thrown from lockCanvas() method.
- WindowManager.BadTokenException: This exception is thrown at the time of trying to view an invalid WindowManager.LayoutParamstoken
What are the states in an activity?↑
There are four states in an activity. These include the following.
- Active state: In this state, the activity is in the foreground.
- Paused state: In this state, the activity is in the background and visible.
- Stopped state: in this state, the activity is at the background but no visible or even hidden or obscure other activities.
- Destroyed state: In this state, the activity is completely terminated or killed or removed.
What is DDMS?↑
DDMS(Dalvik Debug Monitor Server) is a debugging tool in the Android platform. It gives the following list of debugging features:
- Port forwarding services
- Thread and heap information
- Screen capture on the device
- Network traffic tracking
- Incoming call and SMS spoofing
- Location data spoofing
What is sleep mode in Android?↑
In sleep mode, the CPU sleeps and doesn't accept any commands from android device except Radio interface layer and alarm.
What is a visible activity?↑
A visible activity is one that sits behind a foreground dialog. It is actually visible to the user, but not necessarily being in the foreground itself.
Is there a case wherein other qualifiers in multiple resources take precedence over locale?↑
Yes, there are actually instances wherein some qualifiers can take precedence over locale. There are two known exceptions, which are the MCC (mobile country code) and MNC (mobile network code) qualifiers.
What is a retained Fragment?↑
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, signaling the system to retain the current instance of the fragment when the activity is recreated.
What is the purpose of addToBackStack() while commiting fragment transaction?↑
By calling addToBackStack(), the replace transaction is saved to the back stack so the user can reverse the transaction and bring back the previous fragment by pressing the Back button.
What is the use of WebView in Android?↑
WebView is a view that display web pages inside your application. According to Android, “this class is the basis upon which you can roll your own web browser or simply display some online content within your Activity. It uses the WebKit rendering engine to display web pages and includes methods to navigate forward and backward through a history, zoom in and out, perform text searches and more. In order to add WebView to your application, you have to add
Can you deploy executable JARs on android? Which package is supported by it?↑
No, Android does not support JAR deployments. Applications are packed into Android Package(.apk) using Android Asset Packaging Tool (APT) and then deployed on to the Android platform.
What is an intent in Android?↑
An intent is a messaging object that is used to request an action from other components of an application. It can also be used to launch an activity, send SMS, send an email, display a web page, etc.
It shows notification messages to the user from within an Android-enabled device. It alerts the user of a particular state that occurred. There are two types of intents in Android:
- Implicit Intent: Used to invoke the system components.
- Explicit Intent: Used to invoke the activity class.