June 27, 2022

Advanced android interview questions

 What is Application class?

The Application class in Android is the base class within an Android app 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 your application/package is created.


What is onSavedInstanceState() and onRestoreInstanceState() in activity?

onSavedInstanceState() - This method is used to store data before pausing the activity.

onRestoreInstanceState() - This method is used to recover the saved state of an activity when the activity is recreated after destruction. So, the onRestoreInstanceState() receive the bundle that contains the instance state information.


What is the difference between FragmentPagerAdapter vs FragmentStatePagerAdapter?

FragmentPagerAdapter: Each fragment visited by the user will be stored in the memory but the view will be destroyed. When the page is revisited, then the view will be created not the instance of the fragment.

FragmentStatePagerAdapter: Here, the fragment instance will be destroyed when it is not visible to the user, except the saved state of the fragment.


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 are ViewGroups and how they are different from the Views?

View: View objects are the basic building blocks of User Interface(UI) elements in Android. View is a simple rectangle box which responds to the user’s actions. Examples are EditText, Button, CheckBox etc. 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.


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 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). For example, if you take an intent for ACTION_BATTERY_CHANGED to get battery change events: 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.


What is the relationship between the life cycle of an AsyncTask and an Activity? What problems can this result in? How can these problems be avoided?

An AsyncTask is not tied to the life cycle of the Activity that contains it. So, for example, if you 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.

Then, 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 the 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 . Rather, 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 1 thread and each task runs one after the other.


What is commit() and apply() in SharedPreferences?

commit() returns a boolean value of success or failure immediately by writing data synchronously.

apply() is asynchronous and it won't return any boolean response. If you have an apply() outstanding and you are performing commit(), then the commit() will be blocked until the apply() is not completed.


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


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.


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 are the access modifiers you know? What does each one do?

There are four access modifiers in Java language (from strictest to the most lenient):

private variables, methods, constructors or inner classes are only visible to its' containing class and its' methods. This modifier is most commonly used, for example, to allow variable access only through getters and setters or to hide underlying implementation of classes that should not be used by user and therefore maintain encapsulation. Singleton constructor is also marked private to avoid unwanted instantiation from outside.

Default (no keyword is used) this modifier can be applied to classes, variables, constructors and methods and allows access from classes and methods inside the same package.

protected can be used on variables, methods and constructors therefore allowing access only to subclasses and classes that are inside the same package as protected members' class.

public modifier is widely-used on classes, variables, constructors and methods to grant access from any class and method anywhere. It should not be used everywhere as it implies that data marked with public is not sensitive and can not be used to harm the program.


Can an Interface implement another Interface?

Yes, an interface can implement another interface (and more than one), but it needs to use extends, rather than implements keyword. And while you can not remove methods from parent interface, you can add new ones freely to your sub-interface.


What does it means to say that a String is immutable?

It means that once created, String object's char[] (its' containing value) is declared final and, therefore, it can not be changed during runtime.


What is String.intern()? When and why should it be used?

String.intern() is used to mange memory in Java code. It is used when we have duplicates value in different strings. When you call the String.intern(), then if in the String pool that string is present then the equals() method will return true and it will return that string only.


What is garbage collector? How does it work?

All objects are allocated on the heap area managed by the JVM. As long as an object is being referenced, the JVM considers it alive. Once an object is no longer referenced and therefore is not reachable by the application code, the garbage collector removes it and reclaims the unused memory.


Android Interview Questions 2

 Describe different types of Services in Android ?

A Service is an application component that can perform long-running operations in the background, and it doesn't provide a user interface. It can run in the background, even when the user is not interacting with your application. These are the three different types of services:

  • Foreground Service: A foreground service performs some operation that is noticeable to the user. For example, we can use a foreground service to play an audio track.
  • Background Service: A background service performs an operation that isn’t directly noticed by the user. In Android API level 26 and above, there are restrictions to using background services and it is recommended to use WorkManager in these 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. A bound service runs only as long as another application component is bound to it.


How can two distinct Android apps interact?

At the simplest level there are two different ways for apps to interact on Android: via Intents, passing data from one application to another; and through Services, where one application provides functionality for others to use.


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, signaling the system to retain the current instance of the fragment when the activity is recreated.


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.


What is a JobScheduler?

The JobScheduler API performs an operation for your application when a set of predefined conditions are met (such as when a device is plugged into a power source or connected to a Wi-Fi network). This allows your app to perform the given task while being considerate of the device's battery at the cost of timing control.

Unlike the AlarmManager class, the timing isn't exact. Compared to a custom SyncAdapter or the AlarmManager, the JobScheduler supports batch scheduling of jobs. The Android system can combine jobs so that battery consumption is reduced. JobManager makes handling uploads easier as it handles automatically the unreliability of the network. It also survives application restarts. Here are example when you would use this job scheduler:

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



What is the ViewHolder pattern? Why should we use it?

Every time when the adapter calls getView() method, the findViewById() method is also called. This is a very intensive work for the mobile CPU and so affects the performance of the application and the battery consumption increases. ViewHolder is a design pattern which can be applied as a way around repeated use of findViewById(). A ViewHolder holds the reference to the id of the view resource and calls to the resource will not be required after you "find" them: Thus performance of the application increases.


What is the difference between Handler vs AsyncTask vs Thread?

The Handler class can be used to register to a thread and provides a simple channel to send data to this thread. A Handler allows you communicate back with the UI thread from other background thread.

The AsyncTask class encapsulates the creation of a background process and the synchronization with the main thread. It also supports reporting progress of the running tasks.

And a Thread is basically the core element of multithreading which a developer can use with the 
following disadvantage:
  • Handle synchronization with the main thread if you post back results to the user interface
  • No default for canceling the thread
  • No default thread pooling
  • No default for handling configuration changes in Android


What is the difference between compileSdkVersion and targetSdkVersion?

The compileSdkVersion is the version of the API the app is compiled against. This means you can use Android API features included in that version of the API (as well as all previous versions, obviously). If you try and use API 16 features but set compileSdkVersion to 15, you will get a compilation error. If you set compileSdkVersion to 16 you can still run the app on a API 15 device as long as your app's execution paths do not attempt to invoke any APIs specific to API 16.

The targetSdkVersion has nothing to do with how your app is compiled or what APIs you can utilize. The targetSdkVersion is supposed to indicate that you have tested your app on (presumably up to and including) the version you specify. This is more like a certification or sign off you are giving the Android OS as a hint to how it should handle your app in terms of OS features.



What is the difference between a Bundle and an Intent?

A Bundle is a collection of key-value pairs.

However, an Intent is much more. It contains information about an operation that should be performed. This new operation is defined by the action it can be used for, and the data it should show/edit/add. The system uses this information for finding a suitable app component (activity/broadcast/service) for the requested action.


What is an Intent? Can it be used to provide data to a ContentProvider? Why or why not?

The Intent object is a common mechanism for starting new activity and transferring data from one activity to another. However, you cannot start a ContentProvider using an Intent.

When you want to access data in a ContentProvider, you must instead use the ContentResolver object in your application’s Context to communicate with the provider as a client. The ContentResolver object communicates with the provider object, an instance of a class that implements ContentProvider. The provider object receives data requests from clients, performs the requested action, and returns the results.



What is the difference between Service and IntentService? How is each used?

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 is a broadcast receiver?

The broadcast receiver communicates with the operation system messages such as “check whether an internet connection is available,” what the battery label should be, etc.


Is it possible to create an activity in Android without a user interface ?

Yes, an activity can be created without any user interface. These activities are treated as abstract activities.


Android Interview Questions 1

What’s Android?

Android is a Linux-based, open-sourced operating system commonly found on mobile devices, such as smartphones and tablets. It’s a kernel-based system that gives developers the flexibility to design and deploy simple and/or advanced apps.


Explain the Android SDK?

This is a set of tools that Android developers use in order to develop or write apps. It features a graphical user interface that emulates a handheld, Android-driven environment, making it easier for developers to create, test, and debug their code.

The tools include:

  • Dalvik Debug Monitoring Services
  • Android Emulator
  • Android Asset Packaging Tool
  • Android Debug Bridge


What is use of AndroidManifest.xml file?

AndroidManifest.xml file is responsible to protect the application from accessing any protected parts by providing the permissions. Every app project has an AndroidManifest.xml file which is also the root of the project source set. This file contains information about your package, Android operating system, the Android build tools, Google Play, and other including components of the application such as activities, content providers, services, broadcast receivers, etc.


What is an android application architecture?

The Android architecture consists of:

  • Android Framework
  • Android Applications
  • Linux Kernel
  • Libraries


Name the basic tools for developing an Android App?

The tools used for development are:

  • JDK
  • SDK Tools
  • Eclipse+ADT Plugin

What does APK mean?

It’s short for Android Packaging Kit. Every file in the Android packaging key is compressed into a single file, the APK.


What are Activities?

These are the parts of a mobile app that a user sees and interacts with. It represents a Graphic User Interface (GUI), representing one Android screen.


State the life cycle methods of Android activities?

There are seven lifecycle methods of Android activities. They are:

  • On create()
  • On start()
  • On resume()
  • On pause()
  • On stop()
  • On restart()
  • On destroy()


What are the four essential activity states?

The four states are:

  • Active: The activity is at the top of  the stack, running in the foreground
  • Paused: The activity is still visible but cannot receive user input events; it’s in the background
  • Stopped: The activity is invisible and consequently is paused, and obscured or hidden by a different activity
  • Destroyed: The activity’s process has been killed, completed, or terminated


What is a fragment in Android?

The fragment in Android is as follows.

A fragment has its own layout and behavior with its own life cycle callbacks.

Fragments can be added or removed in an activity while the activity is running and used in multiple activities.

Multiple fragments can be combined in a single activity to build a multi-pane UI.

The fragment life cycle is closely related to the life cycle of its host activity which means when the activity is paused, all the fragments available in the activity will also be stopped

Fragments were added to the Android API in the Honeycomb version of Android API version 11.


What’s a content provider?

Content providers share information between different Android applications. They allow users to access data within an application. Examples include contact information, images, video, and audio.


What’s an intent in the context of Android? Describe the different types?

Much what it sounds like, it’s the intention to perform an action, a message that is passed between components. Intents request actions from a different component, such as sending an email, opening a web page, or launch a given activity. The two types are:

  • Implicit Intent This is where the intent doesn’t define the target component, requiring the Android system to conduct an evaluation of the components.
  • Explicit Intent On the other hand, the explicit intent directly identifies the target component.


What’s a sticky intent?

This is a broadcast using the send sticky broadcast() method. The intent sticks around after the broadcast, which allows others to collect data from it.


What is a Pending Intent?

A Pending Intent is an action to require in the future. It allows you to pass a future Intent to a different application and permit that application to execute the Intent.


What’s a “bundle” in Android?

Bundles are used to pass the required data to sub-folders


What is ANR?

This is an acronym for Application Not Responding, a pop-up or notification that kicks in when the application is experiencing lag time for the user due to too many functions being performed simultaneously.


What's the difference between onCreate() and onStart()?

The major difference between onCreate() and onStart() is as follows.

onCreate() is called when the Activity is created; that is, it is launched or started. (Additionally, this triggers when the orientation is changed.) It is called again when the process is killed, then returned to.

while onStart() called following onCreate() at startup. Additionally, it is also called when the app is navigated back to after onStop() (and following onRestart()), which occurs after the Activity is no longer visible (which is during the time that "the user can see the activity on-screen, though it may not be in the foreground and interacting with the user").


 What is service in Android? List its types?

Services in Android are a component that acts as an application to run in the background in order to perform long-running operation tasks.

The types of Services are listed below:

  • Background Services
  • Foreground Services
  • Bound Services

Explian the use of AsyncTasks?

Android AsyncTask going to do background operation on the background thread and update on the main thread. In android, We can't directly touch the background thread to the main thread in android development. asyncTask helps us to make communication between the background thread to the main thread.


Explain different launch modes in Android?

Different launch modes are explained below:

Android Launch mode 'Standard' — Multiple instances every time, A very default launch mode!

Launch mode 'SingleTop' — Multiple instances Conditionally

Specialized Launch mode 'SingleTask' — Single instance throughout System.

Specialized Launch mode 'SingleInstance' — Single instance throughout System.


What is Proguard?

Proguard detects and removes unused classes, fields, methods, and attributes. Mobile app development companies use the Proguard in android, it optimizes bytecode and removes unused instructions. It renames the remaining classes, fields, and methods by using short meaningless names.


What is the difference between Serializable and Parseable?

Serializable is a standard Java interface. It is not a part of the Android SDK. Its simplicity is its biggest beauty. Just by implementing this interface the POJO will be ready to jump from one particular activity to another. There is another interface known as parseable. It is a part of the Android SDK. Paracelable was specifically designed in a way that there is no reflection left while using.


Give a brief idea about Android application architecture?

The architecture of Android application has few components, which have their functions to perform:

Service: It performs the background functions

Intent: Performs the interconnection function between activities and data passing mechanism

Resource: Externalization it is used to perform strings and graphics functions

Notification: This shows the lights, sound, icon, notification, incoming chats messages dialogue box, etc.

Content providers: It shares the data between applications.


What are few exceptions in Android?

These are the following exceptions in Android:

  • Inflate exception
  • Surface.out of resource exception
  • Surface holder bad surface type exception
  • Window manager took exception.


Explain Orientation?

Orientation is set using set orientation (), dictates whether the linear layout is represented as a row or else as a column. There the values are set as HORIZONTAL or VERTICAL.


what is the differentiate between Activities and Services?

Activities can be closed or can be terminated easily as and when the user wants to. Services are designed to run on the background or behind the scenes and can act independently. Most of the services run on a continuous basis regardless of their certain or no certain activities been executed.


What are runnable in android?

Runnable is a concurrent unit of execution in Android. It is also a class that implements a Runnable interface. The Runnable interface is used extensively to execute code in Threads.