Android Interview

Android Architecture
android architechture

What are Android Components? 
  •  Activities
  •  Broadcast receivers
  •  Services
  •  Content Providers

What is an Application class?

  • An Application class is a base class in Android Application that starts before all other classes or components like Activities or services. In this class, you can maintain your application's global state. 

What is a Context? What are the different types of Contexts?

  • A Context is like a handle to the environment of currently running applications. It provides services like resolving resources, obtaining access to databases and preferences, and so on. We have two types of context. 
  • Application context: This context is tied to the lifecycle of an Android application. The application context can be used where you need a context whose lifecycle is separate from the current context or when you are passing a context beyond the scope of activity. The scope of application context is throughout the application.
  • Activity Context: This context is tied to the lifecycle of an activity. The activity context should be used when you are passing the context in the scope of an activity or you need the context whose lifecycle is attached to the current context.

What is an Activity?

  • Activities are basically containers or windows to the user interface in which the app draws Android components. This window typically fills the screen but maybe smaller than the screen and float on top of other windows. In Android, one activity implements one screen in an app. For instance, one of an app’s activities may implement a preferences screen, while another activity implements a select photo screen.

Activity Lifecycle
OnCreate(): This is when the view is first created. This is normally where we create views, get data from bundles, etc.
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.
OnPause(): Called as part of the activity lifecycle when an activity is going into the background but has not (yet) been killed.
OnStop(): Called when you are no longer visible to the user.
OnDestroy(): Called when the activity is finishing
OnRestart(): Called after your activity has been stopped, prior to it being started again.

What are the different launch modes available on Android?
There are four launch modes for an Activity in Android as follows:

  • Standard: You can create single or multiple instances of the activity and add to the same or different tasks. It is the default mode if not declared. Example: Let say, you have three activities A -> B -> C in a stack and if you going to launch B again with standard mode, then the new stack will be A -> B -> C -> B.
  • Single top: It works the same as the standard mode, except if there is an activity instance 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 -> C. If we launch C again with the launch mode as singleTop, the new stack will still be A -> B -> C.
  • Single task: 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 as usual. Now if there is an activity stack of 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.
  • Single instance: It works the same as single task 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 -> D. If we launch activity B again with the launch mode as Single Instance, the new activity stack will be: Task1 — A -> B -> C and Task2 — D.

What is an Intent Filter?
  • Intent filters provide the ability to launch an activity-based not only on an explicit request but also an implicit. For example, an explicit request can tell the system to start an activity to send an email in the Gmail app and an implicit request can tell the system to start an activity to send an email screen in any activity that can do the job.  When the system UI asks a user which app to use in performing a task, that’s an intent filter at work. Here's an example of how to declare Intent Filter in Android Manifest:
    <activity android:name=".LoginActivity" android:icon="@drawable/app_icon">
          <action android:name="android.intent.action.SEND" />
          <category android:name="android.intent.category.DEFAULT" />
          <data android:mimeType="text/plain" />

What is the Intent?

It is a kind of message or information that is passed to the Android components. It is used to launch an activity, display a web page, send SMS, send an email, etc. There are two types of intents in Android:
  • Implicit: Implicit intent is when you call system default intent like send an email, send SMS, dial number. Implicit intents do not name a specific component, but instead declare a general action to perform, which allows a component from another app to handle it. For example, if you want to show the user a location on a map, you can use an implicit intent to request that another capable app show a specified location on a map. 
  • Explicit: Explicit intent is when you call an application activity from another activity of the same application. Explicit intents specify which application will satisfy the intent, by supplying either the target app's package name or a fully-qualified component class name. You'll typically use an explicit intent to start a component in your own app, because you know the class name of the activity or service you want to start. For example, you might start a new activity within your app in response to a user action, or start a service to download a file in the background. 

What is AAPT? or Build process in Android:

AAPT (Android Asset Packaging Tool) is a build tool that Android Studio and Android Gradle Plugin use to compile and package your app’s resources. AAPT parses, indexes, and compiles the resources into a binary format that is optimized for the Android platform. Android perform the following action to build apps:
  • First, it compile the resources folder (/res) using the AAPT tool. These are compiled to a single class file called that contains constants.
  • After that, the java source code is compiled to .class files by javac, and then the class files are converted to Dalvik bytecode by the "dx" tool, which is included in the SDK 'tools'. The output is classes.dex.
  • In the final step, the android apk builder which takes all the input and build the apk (android packaging key) file.
What is the Handler?
  • The handler is used for communicating between the background thread and the main thread. It receives messages and writes code on how to handle the message. They run outside of the activity’s lifecycle, so they need to be cleaned up properly or else you will have thread leaks.
  • A Handler class is preferred when we need to perform a background task repeatedly after every second or minute.
  • A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread/message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

What is HandlerThread?
  • HandlerThread is a Handy class to start a thread that has a Looper.
What is a Service?
  • A service is an Android component that doesn't provide any user interface. It performs long-running operations in the background like downloading stuff, playing music, etc. It can run in the background, even when the user is not interacting with the application. By default, service runs on the main UI thread of system that might cause ANR errors. To avoid this error, we can start service by creating a new thread or use an IntentService that can do work in the background. 

    What are the different types of services?
    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 and display a notification. Foreground services continue running even when the user isn't interacting with the app. 
    • Background Service: A background service performs some actions that aren'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. 
    • Bound Service: A service called bound service if 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. 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 by the system.

    When does a Bound Service stop?

    • A Bound Service will stop automatically by the system when all the Application Components bound to it are unbinded.

    What is an Intent Service?
    • IntentService is a Service that can perform tasks using worker thread.

    How to Stop an IntentService?

    • An IntentService automatically stops itself after its job is done. We do not need to explicitly call any methods to stop an IntentService, unlike Service which requires stopSelf() or StopService(intent:Intent).

    When Intent Service is Useful?

    • The IntentService can be used in long tasks usually with no communication to Main Thread. If communication is required, can use Main Thread handler or broadcast intents. Another case of use is when callbacks are needed (Intent triggered tasks).

    What is the difference between 

    • START_NOT_STICKY: If the Android system kills the service after onStartCommand() returns. This flag of service does not recreate the service unless there are pending intents to deliver. We can use it to avoid long-running service when not necessary and when an application can restart any unfinished jobs. 
    • START_STICKY: If the system kills the service after onStartCommand() method. This flag recreates the service and call onStartCommand(), but do not redeliver the last intent. Instead, the system calls onStartCommand() with a null intent unless there are pending intents to start the service. In that case, those intents are delivered. This is suitable for media players based applications that are not executing commands but are running indefinitely and waiting for a job. 
    • START_REDELIVER_INTENT: If the Android system kills the service after onStartCommand(). This flag recreates the service and call onStartCommand() with the last intent that was delivered to the service. Any pending intents are delivered in turn. This is suitable for services that are actively performing a job that should be immediately resumed, such as downloading a file.

    What is the method that differentiates it to make Service run in the background?

    • onHandleIntent() is the method that helps the IntentService to run a particular code block declared inside it, in worker/background thread.

    Advantages of Retrofit over Volley?
    • Retrofit is type-safe. Type safety means that the compiler will validate types while compiling, and throw an error if you try to assign the wrong type to a variable.

    Advantages of Volley over Retrofit?

    • Android Volley has a very elaborate and flexible cache mechanism. When a request is made through Volley, first the cache is checked for Response. If it is found, then it is fetched and parsed, else, it will hit Network to fetch the data. Retrofit does not support cache by default.

    What is the advantage of using Retrofit over AsyncTask?
    • Retrofit reduces boiler plate code by internally using the GSON library which helps to parse the JSON file automatically. Retrofit is a type-safe library. This means - it checks if the wrong data type is assigned to variables at compilation time itself. More use-cases at:

    How to handle the crashing of AsyncTask during screen rotation?

    • The best way to handle AsyncTask crash is to create a RetainFragment, i.e., a fragment without UI as shown in the gist below: We can also avoid this crash by using RxJava instead of AsyncTask as we will be subscribing and unsubscribing at onResume() and onPause() methods respectively.

    How to handle multiple network calls using Retrofit?
    • In Retrofit, we can call the operations asynchronously by using enqueue() method where as to call operations synchronously, we can use execute() method. In addition, we can use zip() operator from RxJava to perform multiple network calls using Retrofit library.

    What is the role of Presenter in MVP?

    • The Presenter is responsible to act as the middle man between View and Model. It retrieves data from the Model and returns it formatted to the View. But unlike the typical MVC, it also decides what happens when you interact with the View.

    What is the advantage of MVVM over MVP?

    • In MVP, Presenter is responsible for view data updates as well as data operations where as in MVVM, ViewModel does not hold any reference to View. It is the View's responsibility to pick the changes from ViewModel. This helps in writing more maintainable test cases since ViewModel does not depend upon View.
    Difference between MVC & MVP & MVVM?
    • MVC is the Model-View-Controller architecture where model refers to the data model classes. The view refers to the xml files and the controller handles the business logic. The issue with this architecture is unit testing. The model can be easily tested since it is not tied to anything. The controller is tightly coupled with the android apis making it difficult to unit test. Modularity & flexibility is a problem since the view and the controller are tightly coupled. If we change the view, the controller logic should also be changed. Maintenance is also an issues. 
    • MVP architecture: Model-View-Presenter architecture. The View includes the xml and the activity/fragment classes. So the activity would ideally implement a view interface making it easier for unit testing (since this will work without a view). Sample Implementation 
    • MVVM: Model-View-ViewModel Architecture. The Model comprises data, tools for data processing, business logic. The View Model is responsible for wrapping the model data and preparing the data for the view. IT also provides a hook to pass events from the view to the model. Sample Implementation

    When to use AsyncTask and when to use services?
    • Services are useful when you want to run code even when your application's Activity isn't open. AsyncTask is a helper class used to run some code in a separate thread and publish results in main thread. Usually AsyncTask is used for small operations and services are used for long running operations.

    What is a Looper?

    • A Looper is a class used to loop through the Message Queue attached to the Thread. By default, a thread halts when the execution completes. But, for Example, if we take Android's Main thread, it should not halt upon execution. Rather it should loop through the runnables(Messages) that its assigned in order to work properly. For more info, refer to this link.

    How to save password safely in Android?
    Using Android Keystore

    String a = “abc”; String b = new String(“abc”); Will a == b ??
    A) It depends. Here with the first statement, i.e, String a = “abc”, JVM will search for a string with “abc” in String constant pool(SCP) and if its not there it will create a new Object. If we wrote second statement similarly, i.e., String b = “abc”, then b will point to same string from SCP. However, String b = new String(“abc”) always creates a new String object.

    What is Alarm Manager?

    • AlarmManager is a class which helps scheduling application code to run at some point of time or particular time intervals in future. When an alarm goes off, the Intent that had been registered for it is broadcast by the system, automatically starting the target application if it is not already running. Registered alarms are retained while the device is asleep (and can optionally wake the device up if they go off during that time), but will be cleared if it is turned off and rebooted.

    What is Pending Intent?

    • A PendingIntent is a token that you give to a foreign application (e.g. NotificationManager, AlarmManager, Home Screen AppWidgetManager, or other 3rd party applications), which allows the foreign application to use your application's permissions to execute a predefined piece of code. It specifies a task that requires to be performed in the future.

    What is ABI Management?
    • Different Android handsets use different CPUs, which in turn support different instruction sets. Each combination of CPU and instruction sets has its own Application Binary Interface, or ABI. The ABI defines, with great precision, how an application's machine code is supposed to interact with the system at runtime. You must specify an ABI for each CPU architecture you want your app to work with. You can checkout the full specifications here
    Why bytecode cannot be run in Android?
    • Android uses DVM (Dalvik Virtual Machine ) rather than using JVM(Java Virtual Machine) that why bytcode can't be run in Andorid.
    What is a BuildType in Gradle? And what can you use it for?
    • Build types define properties that Gradle uses when building and packaging Android apk. A build type defines how a module is built, for example, whether ProGuard is run. A product flavor defines what is built, such as which resources are included in the build. Gradle creates a build variant for every possible combination of your project’s product flavors and build types.
    What’s the difference between commit() and apply() in SharedPreferences? 
    • commit() writes the data synchronously and returns a boolean value of success or failure depending on the result immediately. 
    • apply() is asynchronous and it won’t return any boolean response. Also if there is an apply() outstanding and we perform another commit(). The commit() will be blocked until the apply() is not completed.

    What is an Application Not Responding (ANR) error, and how can you prevent them from occurring in an app?
    • An ANR dialog appears when your UI has been unresponsive for more than 5 seconds, usually because you’ve blocked the main thread. To avoid encountering ANR errors, you should move as much work off the main thread as possible.

    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.
    When might you use a FrameLayout?
    • Frame Layouts are designed to contain a single item, making them an efficient choice when you need to display a single View. If you add multiple Views to a FrameLayout then it’ll stack them one above the other, so FrameLayouts are also useful if you need overlapping Views, for example if you’re implementing an overlay or a HUD element.
    What is View Group? How are they different from 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 the difference between Dialog & DialogFragment?
    A fragment that displays a dialog window, floating on top of its activity's window. This fragment contains a Dialog object, which it displays as appropriate based on the fragment's state. Dialogs are entirely dependent on Activities. If the screen is rotated, the dialog is dismissed. Dialog fragments take care of orientation, configuration changes as well.

    Difference between FragmentPagerAdapter vs FragmentStatePagerAdapter?
    • FragmentPagerAdapter: the fragment of each page the user visits will be stored in memory, although the view will be destroyed. So when the page is visible again, the view will be recreated but the fragment instance is not recreated. This can result in a significant amount of memory being used. FragmentPagerAdapter should be used when we need to store the whole fragment in memory. FragmentPagerAdapter calls detach(Fragment) on the transaction instead of remove(Fragment). 
    • FragmentStatePagerAdapter: the fragment instance is destroyed when it is not visible to the User, except the saved state of the fragment. This results in using only a small amount of Memory and can be useful for handling larger data sets. Should be used when we have to use dynamic fragments, like fragments with widgets, as their data could be stored in the savedInstanceState.Also it won't affect the performance even if there are large number of fragments.

    How would you update the UI of an activity from a background service
    • We need to register a LocalBroadcastReceiver 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. 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. I have detailed a sample implementation on this. You can check it out here

    Difference between Serializable and Parcelable?
    • Serializable is a standard Java interface. Parcelable is an Android specific interface where you implement the serialization yourself. It was created to be far more efficient than Serializable (The problem with this approach is that reflection is used and it is a slow process. This mechanism also tends to create a lot of temporary objects and cause quite a bit of garbage collection.). 
    • Serialization is the process of converting an object into a stream of bytes in order to store an object into memory, so that it can be recreated at a later time, while still keeping the object's original state and data.


    Post a Comment

    We're Social